DhiaEddine Ayadi
DhiaEddine Ayadi

Reputation: 49

Use a string variable inside an if condition in twig

I have a problem in twig which is below :

I want to use a variable which is a string which is a condition ( that i read from a table from a yml file) inside and if statement consider this example.

{% set condition = 'a condition' %}
{% if condition == true ]%
do something
{% endif %} 

Notice : the string used as a variable contains a twig code

How is it possible to do that ??

is there any similar to eval() of php in twig ?

thanx in advance

Upvotes: 1

Views: 980

Answers (1)

Michael Sivolobov
Michael Sivolobov

Reputation: 13300

You can use some tricky hack with is_granted function. It's created to be used for security purposes but it will work for your use case.

is_granted can evaluate Symfony Expressions, then result can be used in conditional statements.

This example works fine for your case:

{% set condition = "true" %}
{% if is_granted(expression(condition)) %}
    CONDITION IS TRUTHY
{% endif %}

To make it work you need to install symfony-expressions and security components:

composer require symfony/expression-language
composer require security

Also if you don't use it for granting access for users to some places in your template it would be better to create own twig function that will execute Symfony Expressions like is_granted do.

Upvotes: 1

Related Questions