Symfony2 - How to access dynamic variable names in

2019-01-09 15:32发布

问题:

I have some variables in twig like

placeholder1
placeholder2
placeholderx

To call them, I am looping through the array of objects "invoices"

{% for invoices as invoice %}
    need to display here the placeholder followed by the invoice id number
    {{ placeholedr1 }}

Any idea? Thank you.

回答1:

I just had the same issue - and using this first answer and after some additional research found the {{ attribute(_context, 'placeholder'~invoice.id) }} should work (_context being the global context object containing all objects by name)



回答2:

I guess you could use the Twig attribute function.

http://twig.sensiolabs.org/doc/functions/attribute.html



回答3:

Instead of using the attribute function, you can access values of the _context array with the regular bracket notation as well:

{{ _context['placeholder' ~ id] }}

I would personally use this one as it's more concise and in my opinion clearer.

If the environment option strict_variables is set to true, you should also use the default filter:

{{ _context['placeholder' ~ id]|default }}

{{ attribute(_context, 'placeholder' ~ id)|default }}

Otherwise you'll get a Twig_Error_Runtime exception if the variable doesn't exist. For example, if you have variables foo and bar but try to output the variable baz (which doesn't exist), you get that exception with the message Key "baz" for array with keys "foo, bar" does not exist.

A more verbose way to check the existence of a variable is to use the defined test:

{% if _context['placeholder' ~ id] is defined %} ... {% endif %}

With the default filter you can also provide a default value, e.g. null or a string:

{{ _context['placeholder' ~ id]|default(null) }}

{{ attribute(_context, 'placeholder' ~ id)|default('Default value') }}

If you omit the default value (i.e. you use |default instead of |default(somevalue)), the default value will be an empty string.

strict_variables is false by default, but I prefer to set it to true to avoid accidental problems caused by e.g. typos.



回答4:

My solution for this problem:

Create array of placeholder(x). Like:

# Options
$placeholders = array(
    'placeholder1' => 'A',
    'placeholder2' => 'B',
    'placeholder3' => 'C',
);

# Send to View ID invoice
$id_placeholder = 2;

Send both variables for view and in your template call:

{{ placeholders["placeholder" ~ id_placeholder ] }}

This print "B".

I hope this help you.



回答5:

I found the solution:

attribute(_context, 'placeholder'~invoice.id)


标签: php symfony twig