Home >Backend Development >PHP Tutorial >How to Access Dynamic Variable Names in Twig?
When working with arrays of objects in Twig, it is often necessary to access variables with dynamic names. This can be achieved using a combination of template syntax and PHP functions.
To access a variable named placeholder{n}, where n is a variable, you can use the attribute function:
{{ attribute(invoices, 'placeholder1') }}
This will return the value of the placeholder1 variable within the current invoices object.
Alternatively, you can directly access values of the context array using bracket notation:
{{ _context['placeholder' ~ id] }}
This approach is generally preferred as it is more concise and clearer. However, it requires setting the strict_variables environment option to true to avoid runtime errors when accessing non-existent variables.
If the strict_variables option is set to true, you should use the default filter to provide a default value for non-existent variables:
{{ _context['placeholder' ~ id]|default('Default value') }}
To check if a variable exists before using it, you can use the defined test:
{% if _context['placeholder' ~ id] is defined %} ... {% endif %}
This approach is more verbose than using the default filter, but it provides more explicit control over exception handling.
The above is the detailed content of How to Access Dynamic Variable Names in Twig?. For more information, please follow other related articles on the PHP Chinese website!