How to write “If string starts with” in Drupal 8 Twig templates

If you ever need to write a “string starts with” comparison in Drupal 8 Twig templates, I just used this approach in a node.html.twig template file and I can confirm that it works:

{% if uri starts with '/foo' %}

More accurately, what I did was to first get the URI for the current Drupal node, and then I perform that test:

{# (1) get the uri for the current node #}
{% set uri = path('entity.node.canonical', {'node': node.id}) %}

{# (2) compare the uri to different patterns i'm interested in #}
{% if uri starts with '/foo' %}
    ...
{% elseif uri starts with '/bar' %}
    ...
{% else %}
    ...
{% endif %}

Note that you can also write a Twig “string ends with” test like this:

{% if 'foobar' ends with 'x' %}

This approach should work in any Drupal 8 “node” template file, such as node.html.twig, node--blog.html.twig, etc.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.