How to pass a variable to form_theme?

2019-06-16 16:26发布

问题:

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 ?

回答1:

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



回答2:

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.



回答3:

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.



标签: symfony twig