drupaltwigdrupal-webform

Twig print values and strings in set statements


This twig template is not DRY.

{% set reviewer_0 = webform_token('[webform_submission:values:reviewer:0:entity:mail:clear]', webform_submission, [], options) %}
{% set reviewer_1 = webform_token('[webform_submission:values:reviewer:1:entity:mail:clear]', webform_submission, [], options) %}
{% set reviewer_2 = webform_token('[webform_submission:values:reviewer:2:entity:mail:clear]', webform_submission, [], options) %}
{% if reviewer_0|length %}{{ reviewer_0 }}{% else %}{% endif %}
{% if reviewer_1|length %},{{ reviewer_1 }}{% else %}{% endif %}
{% if reviewer_2|length %},{{ reviewer_2 }}{% else %}{% endif %}

I tried using the example from twig documentation

{% for i in 0..10 %}
    * {{ i }}
{% endfor %}

like this:

{% for i in 0..10 %}
    {% set reviewer_{{ i }} = webform_token('[webform_submission:values:reviewer:'{{ i }}':entity:mail:clear]', webform_submission, [], options) %}
    {% if reviewer_{{ i }}|length %}{{ reviewer_{{ i }} }}{% else %}{% endif %}
{% endfor %}

But it doesn't work. I think the strings have to be concatenated somehow. How do I create this loop in twig?


Solution

  • Within {% %} you can't use {{ }} too.

    First, you need to update

    webform_token('[webform_submission:values:reviewer:'{{ i }}':entity:mail:clear]', webform_submission, [], options)
    
    into
    
    webform_token('[webform_submission:values:reviewer:' ~ i ~ ':entity:mail:clear]', webform_submission, [], options)
    

    and variable name seems not correct too, you can just remove _{{ i }} part. Each turn it will overridden anyway.

    Regards,