Variable Variable Name in the Branch

I have a branch macro to create a form element with a list like this:

{% 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, this is not very flexible, because I can use objects with the id name and name as the parameter value and label. Before moving to the branch, I use this PHP function:

 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 function objects and use it as the parameter value and label, passing the function field name ( $keycol and $valcol ) and accessing them through the function of the variable name of the PHP variable ( $choice->$keycol and $choice->$valcol ).

Anyway, can I recreate this function as a branch macro?

+8
php twig
source share
1 answer

The attribute function does this: http://twig.sensiolabs.org/doc/functions/attribute.html

 {{ attribute(choice, valCol) }} 
+17
source share

All Articles