出于安全原因,默认情况下,表单标签中的 HTML 内容会被转义。新的 label_html 布尔选项允许表单字段在其标签中包含 HTML 内容,这对于在按钮、链接和复选框/单选按钮标签等中显示某些格式很有用。
// src/Form/Type/TaskType.php
namespace App\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
class TaskType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
// ...
->add('save', SubmitType::class, [
'label' => ' Save',
'label_html' => true,
])
;
}
}
Run Code Online (Sandbox Code Playgroud)
在您的情况下,您可以直接从模板设置表单标签并将路线传递到那里。
{{ form_widget(form.acceptTermsAndConditions, {
label: '<a href="' ~ path("route") ~ '">' ~ "I accept ..."|trans ~ '</a>',
label_html: true
})
}}
Run Code Online (Sandbox Code Playgroud)
由于上面的解决方案不适合我,我使用此处建议的解决方案解决了它:https://gist.github.com/marijn/4137467
好的,所以在这里我是如何做到的:
{% set terms_link %}<a title="{% trans %}Read the General Terms and Conditions{% endtrans %}" href="{{ path('get_general_terms_and_conditions') }}">{% trans %}General Terms and Conditions{% endtrans %}</a>{% endset %}
{% set general_terms_and_conditions %}{{ 'I have read and accept the %general_terms_and_conditions%.'|trans({ '%general_terms_and_conditions%': terms_link })|raw }}{% endset %}
<div>
{{ form_errors(form.acceptGeneralTermsAndConditions) }}
{{ form_widget(form.acceptGeneralTermsAndConditions) }}
<label for="{{ form.acceptGeneralTermsAndConditions.vars.id }}">{{ general_terms_and_conditions|raw }}</label>
</div>
Run Code Online (Sandbox Code Playgroud)
最好的方法是覆盖用于渲染该特定标签的树枝块。
首先,检查文档的表单片段命名部分。然后在表单模板中使用适当的名称创建一个新块。不要忘记告诉 twig 使用它:
{% form_theme form _self %}
Run Code Online (Sandbox Code Playgroud)
对于下一步,请检查默认form_label
块。
您可能只需要其中的一部分,如下所示(我在此处保留默认块名称):
{% block form_label %}
{% spaceless %}
<label{% for attrname, attrvalue in label_attr %} {{ attrname }}="{{ attrvalue }}"{% endfor %}>
<a href="{{ path("route_for_terms") }}">{{ label|trans({}, translation_domain) }}</a>
</label>
{% endspaceless %}
{% endblock %}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6570 次 |
最近记录: |