I feel a bit dummy as I can't make it work..

I'm trying to check if a string contains substring in my twig.

{% set url = url('<current>') %}
{{ url }}

{% if 'my-delivery' in url %}
    //print something
{% endif %}

The url is printed outside the if statement but it doesn't enter the if statement and the url contains 'my-delivery'.

Any idea why it doesn't work?

  • Why not do this in a preprocess hook? Would be easier.
    – Kevin
    Commented Jun 22, 2017 at 16:07
  • You have a point! At some point I sent the url from the preprocess_page but I didn't think to send just the result... Thank you so much! On the other hand I feel a bit embarrassed not being able to write an if in twig!!!
    – Ismini
    Commented Jun 22, 2017 at 16:22
  • IMO conditional output in twig based on URL could be hairy. I can imagine that caching can get in the way of what someone should be seeing.
    – Kevin
    Commented Jun 22, 2017 at 16:30
  • You have one more point! But at this point I don't know if there is any other option to handle what I wanna do. I'm working with field collection items. I load the node edit form in a page using panels and custom block. By default Drupal wraps the field collection item in a table which I want to avoid. So I was thinking to alter the template based on my current page only.
    – Ismini
    Commented Jun 22, 2017 at 16:41

2 Answers 2


The twig function url() returns a render array, when you render it with the twig filter |render you get a markup object and when you render it again you get a string, which you can check whether it contains a substring:

{% set url = url('<current>') %}
{% if 'test' in url|render|render %}
  <p>url contains "test"</p>
{% endif %}

url() returns an array, as 4x4 says. You can see this if you do a for loop on the variable.

path(), however, seems to return a string that you can do your operation on. But it won't include hostname.

  • it gives the path alias. what about the base url? for example, I want 'taxonomy/term/1' not the word 'students' which I used as alias
    – shekoufeh
    Commented Jun 1, 2019 at 8:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.