首页 > 解决方案 > 如何在数组中使用 twig _context?

问题描述

我正在尝试确定是否使用树枝模板中的循环设置了通过连接字符串和变量构建的变量。我在一个简单的示例中使用“_context”来执行此操作,它适用于单个变量:

.php 文件:

$text_1 = 'some text one';
$text_2 = 'some text two';
$text_3 = 'some text three';

树枝文件:

{% for i in 1..3 %}
    <span>{{ _context["text_" ~ i] }}</span>
{% endfor %}

但是现在我正在尝试对数组变量做同样的事情,其中​​键是通过连接字符串和变量来构建的

.php 文件:

$product = array(
    'bullet_1' => 'some text one',
    'bullet_2' => 'some text two',
    'bullet_3' => 'some text three',
);

但是我从树枝文件中获取它们的尝试似乎都没有奏效:我尝试了以下每一项都无济于事

{% for i in 1..3 %}
    {{ _context["product.bullet_" ~ i]] }}
{% endfor %}

失败

{% for i in 1..3 %}
    {{ product._context["bullet_" ~ i] }}
{% endfor %}

失败

{% for i in 1..3 %}
    {{ product[_context["bullet_" ~ i]] }}
{% endfor %}

失败

有任何想法吗?

标签: arraystwig

解决方案


推荐阅读