如何将变量传递给form_theme?
问题描述:
我想主题我的形式,使得该领域的标签显示当前语言环境,像如何将变量传递给form_theme?
名称(中文):
所以我想改写块generic_label这样的:
{# form_theme.html.twig #}
{% block generic_label %}
{% spaceless %}
{% if required %}
{% set attr = attr|merge({'class': attr.class|default('') ~ ' required'}) %}
{% endif %}
<label{% for attrname,attrvalue in attr %} {{attrname}}="{{attrvalue}}"{% endfor %}>{{ label|trans }} (app.session.locale)</label>
{% endspaceless %}
{% endblock %}
并导入它在我的模板:
{% form_theme options 'myBundle:Object:form_theme.html.twig' %}
但应用程序变量在表单模板中不可访问。 如何将变量传递给表单主题?
答
您需要创建表单扩展才能完成。看看
http://toni.uebernickel.info/2011/11/25/how-to-extend-form-fields-in-symfony2.html
学习如何创建扩展。
要访问会话区域设置,请确保注入容器。之后,你将能够得到你想要的任何var值。
答
如果app
变量在表单主题中不可用,则可能是一个错误。我建议你create a ticket。
在此期间,您可以使用当前模板作为主题。喜欢的东西...
{% form_theme form _self %}
{% block field_label %}
{% set attr = attr|merge({ 'for': id }) %}
{% if required %}
{% set attr = attr|merge({ 'class': attr.class|default('') ~ ' required' }) %}
{% endif %}
<label{% for attrname, attrvalue in attr %} {{ attrname }}="{{ attrvalue }}"{% endfor %}>{{ label|trans }} ({{ app.session.locale }})</label>
{% endblock %}
如果您正在使用的Symfony主(2.1)与app.request.locale
取代app.session.locale
。
答
在当前版本的树枝中(与2016年一样),这是可能的。 在模板中使用下面这个样子:
{{ form_row(form.content, {'testvar' : 'this is test variable'}) }}
然后,在你的主题文件,只需使用:
{{testvar}}
当然不是form.content你会使用你所需要的字段名。 干杯, Chris
也不管用,'{%form_theme edit_form _self%} {%block field_label%} {{app.session.locale}} {%endblock%}'给出'变量“app”不存在'。我要创建一张票 – Matthieu 2012-01-08 10:59:17
https://github.com/symfony/symfony/issues/3058 – Matthieu 2012-01-08 11:14:29