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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度