Symfony2表单标签中的HTML而不是纯文本 [英] HTML in Symfony2 form labels instead of plain text
本文介绍了Symfony2表单标签中的HTML而不是纯文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试实现类似这样的东西:
I am trying to implement something like this:
<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>
最接近实现此目标的方法是:
The closest I've come to implement this is through:
<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}}. :)
Is there a better way? Having to specify {{ form.agreeWithTos.vars.id }} is inelegant. :)
推荐答案
在我的表单主题中使用以下代码解决了该问题:
Solved this problem using the following code in my form-theme:
{# ---- 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 %}
然后在表单模板中使用:
in your Form-Template you can then use:
{% 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>'
})
}}
这样,表单主题中的块将应用于页面上的任何复选框.如果还需要使用默认主题,则可以添加参数以启用特殊渲染:
this way, the block from the form-theme would apply to any checkbox on the page. If you need to also use the default-theme, you can add a parameter to enable special-rendering:
{# ---- 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>'
})
}}
这篇关于Symfony2表单标签中的HTML而不是纯文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文