简体   繁体   English

在Twig中将字符串连接为变量

[英]Concatenate String as Variable in Twig

I have a form that generates field per category, so if I have 5 categories, twig will generate 5 category field. 我有一个表单,每个类别生成一个字段,所以如果我有5个类别,twig将生成5个类别字段。

This array consist of 5 categories, so it will loop 5 times. 该数组由5个类别组成,因此它将循环5次。

{% set categories = ['attraction', 'featured_artist', 'co_presentator', 'major_sponsor', 'minor_sponsor'] %}

I'll count the total category and deduct it by 1 for the use of for loop. 我将计算总类别,并使用for循环将其减去1。 We're using in array so it would be like 0,1,2,3.. etc. 我们在数组中使用它就像0,1,2,3 ......等。

{% set total_category = categories|count -1 %}

Now the looping starts here, I have a different column in database, called attraction_image, major_sponsor_image, featured_artist_image. 现在循环从这里开始,我在数据库中有一个不同的列,名为attraction_image,major_sponsor_image,featured_artist_image。 So I have to count the total value in that field per category. 所以我必须计算每个类别该字段的总价值。

{% 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 %}

How can I concatenate string as variable, 如何将字符串连接为变量,

We're calling the total of field like this 我们正在调用这样的字段总数

{% set total_field = details.attraction_image|explode|count %}

But I want to happen is, 但我想要发生的是,

{% set total_field = details.categories[i]_image|explode|count %}

Technically it would be incorrect: 从技术上讲,这是不正确的:

在此输入图像描述

I tried this String Interpolation thing, but still did not work. 我试过这个String Interpolation的东西,但仍然没有用。

{% set total_field = details."#{categories[i]}"_image|explode|count %}

Any solution to this problem? 任何解决这个问题的方法?

You can use the attribute function for this. 您可以使用属性函数 See my similar answer for details. 请参阅我的类似答案了解详情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM