来自 Twig 中的 _multiple_ 变量的变量名
我正在使用 Opencart,并且我有一个非常有用的插件,来自旧版本的 php.我注意到 twig 并不难,我尝试将 php 代码转换为 twig.简单的 ifs/for 循环/回声很容易,但原作者使用动态创建的变量名.
I'm using Opencart and I have a really useful plugin from an older version in php. I noticed that twig isn't that hard and I tried to convert the php code into twig. Simple ifs/for loops/echos were easy enough, but the original author uses dynamically created variable names.
当动态部分仅来自一个变量时,我已经看到使用属性和 _context 的示例.但是当变量名由 2 个、3 个或更多变量部分组成时会发生什么?
I have seen examples using attribute and _context when the dynamic part comes from just one variable. But what happens when the variable name consists of 2, 3, or more variable parts?
这是一个实际的例子(还有很多这样的例子)
This is an actual example (and there are many more like this)
${'var_' . $extension['name'] . '_' . $geo_zone['geo_zone_id'] . '_' . $customer_group['customer_group_id'] . '_order_total_sort_order'};
这是可以实现的,还是与twig完全不相容的思维方式?
Is this something that can be achieved or is it a way of thinking totally incompatible with twig?
我了解我们如何使用动态创建的变量的值.但是是否可以在不知道各种组件的情况下对其进行初始化?或者检查这样的变量是否存在?在我的特殊情况下,变量是由用户定义的字段创建的,然后可以自由使用,还通过 if 检查.
I understand how we use the value of a dynamically created variable. But is it possible to initialize it without knowing the various components in the first place? Or check if such a variable even exists? In my particular case the variables are created by user defined fields and then used freely, also passing through an if check.
<select name="var_<?= $geo_zone['geo_zone_id']; ?>_= $group['group_id']; ?>_tax_class_id"><option value="0" <?php if(${'var_' . $geo_zone['geo_zone_id'] . '_' . $group['group_id'] . '_tax_class_id'} == 0){ echo'选择';} ?>><?= $text_none;?></选项></select>
我真的不知道这怎么能变成树枝.
I honestly have no idea how this can be turned into twig.
推荐答案
你只是把它们全部连接起来?
You just concat them all?
{% set long_variable_name_here = 'foo' %}
{% set long = 'long' %}
{% set variable = 'variable' %}
{% set name = 'name' %}
{% set here = 'here' %}
{{ attribute(_context, long~'_'~variable~'_'~name~'_'~here) }}
演示
{% set var_1_1_tax_class_id = 0 %}
<select name="var_{{ geo_zone['geo_zone_id'] | default(1) }}_{{ group['group_id']|default(1) }}_tax_class_id">
<option value="0"{{ attribute(_context, 'var_'~geo_zone['geo_zone_id']|default(1)~'_'~group['group_id']|default(1)~'_tax_class_id') | default(-1) == 0 ? ' checked' }}>{{ text_none | default('text') }}</option>
</select>
相关文章