Jonas de Herdt
Jonas de Herdt

Reputation: 451

Execute statement inside conditional

Is it possible to call an executable function inside a Twig conditional statement?

I have a path function and want to output the path if the name variable is empty. Right now I have these two options:

{% path file, 'reference' %} // calling path function
{{ file.name ?: file.path }} // Conditional

But I would like something like:

{% file.name ?: path file, 'reference' %}

Upvotes: 0

Views: 249

Answers (1)

Matias Kinnunen
Matias Kinnunen

Reputation: 8540

Looks like path is a tag instead of a function. If it was a function, you'd use it like this:

{% path(file, 'reference') %}

In comparison, Twig has a function dump, and in Symfony you can use a tag with the same name. Here's how you'd use them:

{{ dump(foo) }} {# function #}
{% dump foo %}  {# tag #}

You see the difference?

If path was a function, both of these would probably be possible:

{{ file.name ?: path(file, 'reference') }}
{% do file.name ?: path(file, 'reference') %}

Both are the same, except the second one doesn't print anything.

Because path seems to be a tag, I don't think it's possible to do what you asked. (It's also possible that it's both a tag and a function. If that's the case, use the function instead of the tag.)

Edit: Are you using Symfony? There's a Twig function path in Symfony, but I don't think there's a Twig tag path. Are you sure your code ({% path file, 'reference' %}) is correct?

Upvotes: 1

Related Questions