douwei8672 2018-06-11 17:24
浏览 58
已采纳

来自Twig中_multiple_变量的变量名

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.

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'};

Is this something that can be achieved or is it a way of thinking totally incompatible with twig?

EDIT: 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 'selected'; } ?>><?= $text_none; ?></option> </select>

I honestly have no idea how this can be turned into twig.

  • 写回答

1条回答 默认 最新

  • douguanci9158 2018-06-12 05:30
    关注

    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) }}
    

    demo


    {% 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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号