1

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

2
  • 2
    Why can't you calculate that condition in PHP and pass it to Twig as a boolean variable? Commented Jun 14, 2021 at 22:03
  • Notice : the string used as a variable contains a twig Commented Jun 15, 2021 at 10:44

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.