variablestwigtimbertemplating-engine

Twig use dynamic variables


I want to display for each user their availability. Therefore I want to concatenate a {{variable}} into {{variable}} (example below).

I have an array of workdays:

$context['workdays'] = [ 'monday', 'tuesday', 'wednesday', 'thursday', 'friday' ];

And some database fields like monday_morning_availability and tuesday_morning_availability etc.

With {{user.monday_morning_availability}} I can display its availability for monday and {{user.tuesday_morning_availability}} for tuesday etc. However I don't want to repeat myself for each day to do this.

I want to call {{ user.workday_morning_availability }} to dynamically insert a variable into the call.

I've tried:

{% for user in users %}
{% for workday in workdays %}
    {{ workday}} : {{ attribute(_context, user.~'workday'~_morning_availability) }}
{% endfor %}
{% endfor %}

But unfortunately that throws an error, see:

Uncaught Exception: Expected name or number

Edit: I might be onto something..

    {% set foobar = workday ~ "_morning_availability" %}

    {{ foobar }}
    {{ workday }} : {{ attribute(_context, user.foobar) }}

Value of foobar is as expected: monday_morning_availability

This however doesn't work when called on the user


Solution

  •     {% set foobar = workday ~ "_morning_availability" %}
    
        {{ workday }} : {{ attribute(user, foobar) }}