我定义了一个模板,为我的表单构建选择下拉输入:
<p id="{{key | ucfirst}}">
<span>{{label}} : </span>
<select required disabled>
{% for d in data %}
<option value="{{attribute(d, optionValue)}}" {{(attribute(d, optionValue) == selectedValue)?'selected'}}>{{attribute(d, optionIntitule)}}</option>
{% endfor %}
</select>
<span><em>{{initialValue | default("")}}</em></span>
</p>
然后我只需要包含它,并向它传递一些数据:
{% include 'selectForm.twig' with {'label': 'Manager'
, 'key': context.manager.id
, 'initialValue': projet.manager.username
, 'data': users
, 'keyValue': 'id'
, 'keyIntitule': 'username'
, 'selectedValue': projet.manager.id) }
%}
它工作正常,但我想做更多。例如,我想在选项的标签中显示一个对最终用户更有用的值:<option>Username (email)</option>
而不是<option>Username</option>
所以我想我不能再使用 attribute
功能。
我以为我可以通过an expression我的模板如下:
{% include 'selectForm.twig' with {..., 'keyIntitule': "#{d.username (d.email)}"} %}
但是表达式是根据直接上下文而不是模板的上下文来计算的。所以它不起作用。
I also tried with template_from_string
但我没有成功(我以前从未使用过这个功能......)
有没有办法将表达式传递给另一个模板,并使其使用自己的上下文来计算表达式?
最佳答案
如果你想阻止直接上下文,你可以使用 include function而不是include tag 。然后您可以通过这种方式禁用上下文(示例取自文档):
{# only the foo variable will be accessible #}
{{ include('template.html', {foo: 'bar'}, with_context = false) }}
关于symfony - 如何将 Twig 表达式作为参数传递给模板,然后使用模板的上下文执行它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28432917/