ZCT
ZCT

Reputation: 329

Twig accessing variables that need a variable expansion

I have the following code in a Twig template:

       {% macro option_display(type) -%}
    {% if server.options_array.options.{{type}}.name is defined %}
        {{server.options_array.options.{{type}}.name}} +${{server.options_array.options.~type~.price}}
    {%else%}
        None
    {% endif %}
{%- endmacro %}

I'm getting this error:

Twig_Error_Syntax: Expected name or number

How should I get it to expand the variable 'type' in that context? I've tried using ~type~ as well (concat).

would be something like $server['options_array']['options'][$type]['name']; in PHP.

Upvotes: 1

Views: 431

Answers (1)

Matias Kinnunen
Matias Kinnunen

Reputation: 8540

Just use the bracket notation:

{% macro option_display(type) -%}
    {% if server.options_array.options[type].name is defined %}
        {{ server.options_array.options[type].name }} +${{ server.options_array.options[type].price }}
    {% else %}
        None
    {% endif %}
{%- endmacro %}

You probably want to also check whether server.options_array.options[type] is defined before checking whether server.options_array.options[type].name is defined.

Furthermore, like the documentation of the macro tag says, "as with PHP functions, macros don't have access to the current template variables." So you probably need to pass the server variable to the macro as well.

So here's a more complete example:

{% macro option_display(server, type) -%}
    {% set option = server.options_array.options[type]|default(null) %}
    {% if option.name is defined %}
        {{ option.name }} +${{ option.price }}
    {% else %}
        None
    {% endif %}
{%- endmacro %}

{% from _self import option_display %}

{{ option_display(server, 'foo') }}
{{ option_display(server, 'bar') }}

Notice that I'm using a helper variable option and the default filter. Without the filter, you'd get a Twig_Error_Runtime exception if the server.options_array.options array doesn't have the key you are using. (Whether you get this exception or not depends on the value of the environment option strict_variables.)

See TwigFiddle

Upvotes: 1

Related Questions