我试图实现这样的事情:
<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>
Run Code Online (Sandbox Code Playgroud)
我最接近实现这一点是通过:
<div>
{{ form_widget(form.agreeWithTos) }}
<label for="{{ form.agreeWithTos.vars.id }}">I agree to the <a href="#">Terms of Service</a></label>
</div>
Run Code Online (Sandbox Code Playgroud)
有没有更好的办法?必须指定{{form.agreeWithTos.vars.id}}是不优雅的.:)
Xov*_*ver 14
感谢最近对 Symfony 的承诺label_html,您可以从Symfony 5.1开始使用:
{{ form_label(
form.privacy,
'I accept the <a href="' ~ path('privacy') ~ '">privacy terms</a>.',
{
'label_html': true,
},
) }}
Run Code Online (Sandbox Code Playgroud)
Mar*_*fuß 11
使用我的表单主题中的以下代码解决了这个问题:
{# ---- 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 %}
Run Code Online (Sandbox Code Playgroud)
在您的表单模板中,您可以使用:
{% 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>'
})
}}
Run Code Online (Sandbox Code Playgroud)
这样,来自表单主题的块将应用于页面上的任何复选框.如果您还需要使用default-theme,则可以添加参数以启用特殊渲染:
{# ---- form-theme.html.twig #}
{% block checkbox_row %}
{% spaceless %}
{% if not useTosStyle %}
{{ parent() }}
{% else %}
{# ... special rendering ... #}
{% endif %}
{% endspaceless %}
{% endblock %}
Run Code Online (Sandbox Code Playgroud)
将使用这样:
{% 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>'
})
}}
Run Code Online (Sandbox Code Playgroud)