是否可以在Twig中使用form_label包装form_widget?

时间:2013-10-23 22:14:30

标签: symfony twig

将其整合到Twig中:

<label class="control-label" for="lastname">Last Name:</label>
<div class="controls">
    <input type="text" id="firstname" name="firstname">
    <span class="help-block">{{ form_errors(form.firstname) }}</span>
</div>

我使用了以下代码段:

{{ form_label(form.firstname, null, {'label_attr': {'class': 'control-label'}}) }}
<div class="controls">
    {{ form_widget(form.firstname) }}
    <span class="help-block">{{ form_errors(form.firstname) }}</span>
</div>

一切正常。

但我的问题是......

是否可以在twig中使用form_label包装form_widget?最终结果应类似

<label class="radio" for="dn">
    <input type="radio" id="dn" name="spotlight" value="1"> Test 1
</label>
<label class="radio" for="gn">
    <input type="radio" id="gn" name="spotlight" value="1"> Test 2
</label>
<span class="help-block">Errors</span>

我可以使用除form_labelform_widget以外的任何其他内容来获得相同的结果吗?

1 个答案:

答案 0 :(得分:1)

您只能在一个文件中更改form_row()输出的显示:

{% form_theme form _self %}

{% block form_row %}
    <div class="form_row">
        {% if label is not sameas(false) %}
            {% if not compound %}
                {% set label_attr = label_attr|merge({'for': id}) %}
            {% endif %}
            {% if required %}
                {% set label_attr = label_attr|merge({'class': (label_attr.class|default('') ~ ' required')|trim}) %}
            {% endif %}
            {% if label is empty %}
                {% set label = name|humanize %}
            {% endif %}
            <label{% for attrname, attrvalue in label_attr %} {{ attrname }}="{{ attrvalue }}"{% endfor %}>{{ label|trans({}, translation_domain) }}
        {% endif %}

        {{ form_widget(form) }}

        {% if label is not sameas(false) %}
            </label>
        {% endif %}

        {{ form_errors(form) }}
    </div>
{% endblock form_row %}

显示您的字段:

{{ form_row(form.firstname) }}

<label>现在在字段之前打开,在字段之后关闭。

我从default theme获取原始代码并使用cookbook entry Form Theming in Twig > Method 1: Inside the same Template as the Form

如果您想将自己的想法应用于所有字段,请考虑使用form customization来更改所有字符串中{{ form_row(....) }}的显示。

相关问题