简体   繁体   English

树枝中的变量名称

[英]Variable variable name in twig

I have a twig macro for creating a combo box form element like this : 我有一个用于创建组合框表单元素的twig宏,如下所示:

{% macro select(name, label, choices, help, value) %}
<div class="control-group">
    <label class="control-label" for="{{ name }}">{{ label }}</label>
    <div class="controls">
        {% for choice in choices %}
            {% if value is not empty and value == choice.id %}
                <option value="{{ choice.id }}" selected="selected">{{ choice.code }} - {{ choice.name }}</option>
            {% else %}
                <option value="{{ choice.id }}">{{ choice.name }}</option>
            {% endif %}
        {% endfor %}
        <p class="help-block">{{ help }}</p>
    </div>
</div>
{% endmacro %}

As you can see, it's not very flexible because I can only use objects with id and name field as the option value and label. 正如您所看到的,它不是很灵活,因为我只能使用带有id和name字段的对象作为选项值和标签。 Before migrating to twig, I use this PHP function : 在迁移到twig之前,我使用这个PHP函数:

function form_select($name, $label, $choices, $keycol, $valcol, $value=null, $help=null)
{ ?>
<div class="control-group">
    <label class="control-label" for="<?php echo $name; ?>"><?php echo $label; ?></label>
    <div class="controls">
        <select name="<?php echo $name; ?>" class="span7" id="<?php echo $name; ?>">
            <?php foreach ($choices as $choice) : ?>
                <option value="<?php echo $choice->$keycol; ?>" <?php if ($choice->$keycol == $value) echo "selected"; ?>>
                    <?php echo $choice->$valcol; ?>
                </option>
            <?php endforeach; ?>
        </select>
        <p class="help-block"><?php echo $help; ?></p>
    </div>
</div>
<?php }

With this function I can send arbitrary objects to the function and use it as the option value and label by passing the field name to the function ( $keycol and $valcol ) and accessing them via PHP's variable variable name feature ( $choice->$keycol and $choice->$valcol ). 使用此函数,我可以将任意对象发送到函数,并将其用作选项值和标签,方法是将字段名称传递给函数( $keycol$valcol ),并通过PHP的变量名称功能访问它们( $choice->$keycol$choice->$valcol )。

Is there anyway I can recreate this function as a twig macro? 无论如何我可以重新创建这个功能作为树枝宏?

属性函数执行此操作: http//twig.sensiolabs.org/doc/functions/attribute.html

{{ attribute(choice, valCol) }}

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

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