symfony - 如何将 Twig 表达式作为参数传递给模板,然后使用模板的上下文执行它?

标签 symfony templates twig

我定义了一个模板,为我的表单构建选择下拉输入:

<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/

相关文章:

php - 在 Twig 中是相同的 (===)

php - Composer 在 docker 中使用自己的 Symfony 路径(加载旧文件)

c++ - C++ 模板类的成员函数中的类型/值不匹配

javascript - VueJs 数据不会显示

symfony - 使用变量作为 twig 中的散列键(作为 path() 或 |trans 中的参数)

symfony - assetic:dump 命令不转储图像

symfony - BehatContext 和 MinkContext 之间的混淆

php - 错误 : [PDOException] SQLSTATE[HY000] [2002] No such file or directory

symfony - 如何在 Symfony (Twig) 中包含可重用的小部件?

c++ - 函数模板部分特化 - 有什么解决方法吗?