Symfony2 表单标签中的 HTML,而不是纯文本

2022-08-30 23:06:55

我正在尝试实现这样的东西:

<div>
    <input type="checkbox" name="checkbox" id="checkbox_id" />
    <label for="checkbox_id">I agree to the <a href="/tos">Terms of Service</a></label>
</div>

我最接近实现这一点的方法是:

<div>
    {{ form_widget(form.agreeWithTos) }}
    <label for="{{ form.agreeWithTos.vars.id }}">I agree to the <a href="#">Terms of Service</a></label>
</div>

有没有更好的方法?必须指定 {{ form.agreeWithTos.vars.id }} 是不优雅的。:)


答案 1

在我的表单主题中使用以下代码解决了此问题:

{# ---- form-theme.html.twig #}
{% block checkbox_row %}
{% spaceless %}
<div>
    {{ form_errors(form) }}

    <label class="checkbox" for="{{ form.vars.id }}">
        {{ form_widget(form) }}
        {{ label|default(form_label(form)) | raw }}
    </label>
</div>
{% endspaceless %}
{% endblock %}

在您的表单模板中,您可以使用:

{% form_theme form '::form-theme.html.twig' %}

{{form_row(form.termsOfServiceAccepted, {
        'label' : 'I have read and agree to the <a href="#">Terms and conditions</a>'
    })
}}

这样,表单主题中的块将应用于页面上的任何复选框。如果还需要使用默认主题,则可以添加一个参数来启用特殊渲染:

{# ---- form-theme.html.twig #}
{% block checkbox_row %}
{% spaceless %}
    {% if not useTosStyle %}
        {{ parent() }}
    {% else %}
        {# ... special rendering ... #}
    {% endif %}
{% endspaceless %}
{% endblock %}

这将像这样使用:

{% form_theme form '::form-theme.html.twig' %}

{{form_row(form.termsOfServiceAccepted, {
        'useTosStyle' : true,
        'label' : 'I have read and agree to the <a href="#">Terms and conditions</a>'
    })
}}

答案 2

由于最近对 Symfony 的提交,您可以从 Symfony 5.1 开始使用:label_html

{{ form_label(
    form.privacy,
    'I accept the <a href="' ~ path('privacy') ~ '">privacy terms</a>.', 
    {
        'label_html': true,
    },
) }}

推荐