如何在twig中访问动态变量名


How to access dynamic variable names in twig?

我在twig中有一些变量,比如

placeholder1
placeholder2
placeholderx

要调用它们,我循环遍历对象数组"发票"

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

我刚刚遇到了同样的问题-使用这个第一个答案,经过一些额外的研究发现{{ attribute(_context, 'placeholder'~invoice.id) }}应该工作(_context是包含所有对象的名称的全局上下文对象)

除了使用attribute函数,您还可以使用常规括号符号访问_context数组的值:

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

我个人会使用这个,因为它更简洁,在我看来更清晰。

如果环境选项strict_variables被设置为true,您还应该使用default过滤器:

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

否则,如果变量不存在,您将获得Twig_Error_Runtime异常。例如,如果您有变量foobar,但尝试输出变量baz(不存在),则会得到消息Key "baz" for array with keys "foo, bar" does not exist的异常。

检查变量是否存在的更详细的方法是使用defined测试:
{% if _context['placeholder' ~ id] is defined %} ... {% endif %}

对于default过滤器,您还可以提供一个默认值,例如null或字符串:

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

如果省略默认值(即使用|default代替|default(somevalue)),默认值将是一个空字符串。

strict_variables默认为false,但我更倾向于将其设置为true,以避免因拼写错误等导致的意外问题。

我想你可以使用Twig attribute函数。

https://twig.symfony.com/doc/3.x/functions/attribute.html

我对这个问题的解决方案:

创建占位符数组。如:

# Options
$placeholders = array(
    'placeholder1' => 'A',
    'placeholder2' => 'B',
    'placeholder3' => 'C',
);
# Send to View ID invoice
$id_placeholder = 2;

发送视图和模板调用的两个变量:

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

这个打印"B"

我找到了解决方案:

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