user1439590
user1439590

Reputation: 329

Twig - interpolating variables

I have the following:

{% if promo.monday_unavailable == 1 %} 
    not available mondays 
{% elseif promo.monday_available == 1%}
    available mondays 
{% else %}
    available mondays from {{promo.monday_start}} until {{promo.monday_end}}
{% endif %}
<br />
{% if promo.tuesday_unavailable == 1 %} 
    not available tuesdays 
{% elseif promo.tuesday_available == 1%}
    available tuesdays 
{% else %}
    available tuesdays from {{promo.tuesday_start}} until {{promo.tuesday_end}}
{% endif %}
<br />

...

That I would like to do for each day of the week.

I'm wondering if there is a way I can simplify the code to read

{% for i in ['monday','tuesday','wednesday','thursday','friday','saturday','sunday'] %}

{% if promo.~i~"_unavailable" == 1 %} 
    not available mondays 
{% elseif promo.~i~"_available" == 1%}
    available mondays 
{% else %}
    available mondays from {{promo.~i~"_start"}} until {{promo.~i~"_end"}}
{% endif %}
<br />

{% endfor %}

With Twig.

Any help would be appreciated. I'm at a loss for what keywords to search for anymore.

Upvotes: 6

Views: 11834

Answers (3)

ducnh241
ducnh241

Reputation: 31

You can try using my code

{% for i in ['monday','tuesday','wednesday','thursday','friday','saturday','sunday'] %}
    {% set key = i ~ '__unavailable' %}

    {% if (promo[key]) eq something %}
        //
    {% endif %}
{% endfor}

Upvotes: -1

Niclas
Niclas

Reputation: 1406

I know this is an old thread but twig has support for inline interpolation like:

{{i18n("language_#{langId}")}}

Important that the string to interpolated is with double-quotes.

Upvotes: 15

user1439590
user1439590

Reputation: 329

Found answer by mashing my forehead on the keyboard.

rather than

{% if promo.~i~"_unavailable" == 1 %} 

use

{% promo[i~"_unavailable"] == 1 %)

Upvotes: 4

Related Questions