How to pass a variable to form_theme?

2019-06-16 16:10发布

I want to theme my form so that the field's label show the current locale, something like

Name (en) :

So I would like to rewrite block generic_label like that :

{# 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 %}

and import it in my template :

{% form_theme options 'myBundle:Object:form_theme.html.twig' %}

but the app variable is not accessible in the form template. How can I pass a variable to a form theme ?

标签: symfony twig
3条回答
Bombasti
2楼-- · 2019-06-16 17:04

If the app variable is not available in the form theme it may be a bug. I suggest you create a ticket.

In the meantime you can use the current template as a theme. Something like...

{% 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 %}

If you are using Symfony master (2.1) replace app.session.locale with app.request.locale.

查看更多
放我归山
3楼-- · 2019-06-16 17:08

You need to create a form extension in order to get it done. Take a look at

http://toni.uebernickel.info/2011/11/25/how-to-extend-form-fields-in-symfony2.html

to learn how to create the extension.

To have access to session locale, make sure to inject the container. After that you'll be able to get any var value you want.

查看更多
地球回转人心会变
4楼-- · 2019-06-16 17:11

In current version of twig (as for 2016) it is possible. In your template use the following like this:

{{ form_row(form.content, {'testvar' : 'this is test variable'}) }}

Then, in your theme file, just use:

{{testvar}}

of course instead of form.content you will use the field name you need. Cheers, Chris

查看更多
登录 后发表回答