连接字符串作为 Twig 中的变量
Concatenate String as Variable in Twig
我有一个为每个类别生成字段的表单,所以如果我有 5 个类别,twig 将生成 5 个类别字段。
这个数组包含5个类别,所以会循环5次。
{% set categories = ['attraction', 'featured_artist', 'co_presentator', 'major_sponsor', 'minor_sponsor'] %}
我统计一下总类别减1,因为for循环的使用。我们在数组中使用,所以它就像 0,1,2,3.. 等
{% set total_category = categories|count -1 %}
现在循环从这里开始,我在数据库中有一个不同的列,称为 attraction_image、major_sponsor_image、featured_artist_image。所以我必须计算每个类别该字段的总价值。
{% for i in 0..total_category %}
<div class="increment-field-container" data-increment-host="{{ categories[i] }}">
{% set total_field = details.attraction_image|explode|count %}
</div>
{% endfor %}
如何连接字符串作为变量,
我们这样称呼总字段
{% set total_field = details.attraction_image|explode|count %}
但我想发生的是,
{% set total_field = details.categories[i]_image|explode|count %}
从技术上讲这是不正确的:
我试过这个字符串插值,但还是不行。
{% set total_field = details."#{categories[i]}"_image|explode|count %}
这个问题有什么解决办法吗?
您可以使用attribute function for this. See my 了解详情。
我其实是在搞清楚之后才发现这个的。但是我解决这个问题的方法正如理查德指出的那样,使用属性方法:
{% set field_1 = input_get('field_1') %}
{{attribute(blogs, field_1) }}
无论你有什么 field_1 se 作为(例如 'layouts'),它都等同于
blogs.layouts
希望对您有所帮助!
我有一个为每个类别生成字段的表单,所以如果我有 5 个类别,twig 将生成 5 个类别字段。
这个数组包含5个类别,所以会循环5次。
{% set categories = ['attraction', 'featured_artist', 'co_presentator', 'major_sponsor', 'minor_sponsor'] %}
我统计一下总类别减1,因为for循环的使用。我们在数组中使用,所以它就像 0,1,2,3.. 等
{% set total_category = categories|count -1 %}
现在循环从这里开始,我在数据库中有一个不同的列,称为 attraction_image、major_sponsor_image、featured_artist_image。所以我必须计算每个类别该字段的总价值。
{% for i in 0..total_category %}
<div class="increment-field-container" data-increment-host="{{ categories[i] }}">
{% set total_field = details.attraction_image|explode|count %}
</div>
{% endfor %}
如何连接字符串作为变量,
我们这样称呼总字段
{% set total_field = details.attraction_image|explode|count %}
但我想发生的是,
{% set total_field = details.categories[i]_image|explode|count %}
从技术上讲这是不正确的:
我试过这个字符串插值,但还是不行。
{% set total_field = details."#{categories[i]}"_image|explode|count %}
这个问题有什么解决办法吗?
您可以使用attribute function for this. See my
我其实是在搞清楚之后才发现这个的。但是我解决这个问题的方法正如理查德指出的那样,使用属性方法:
{% set field_1 = input_get('field_1') %}
{{attribute(blogs, field_1) }}
无论你有什么 field_1 se 作为(例如 'layouts'),它都等同于
blogs.layouts
希望对您有所帮助!