【发布时间】:2013-08-11 08:12:07
【问题描述】:
我在我的 symfony 应用程序中为我的表单覆盖了 Twig 模板,这样我就可以更好地控制复选框的标签。
但是,我在使用复选框标签时遇到问题。
这是我在自定义模板文件中覆盖的代码:
{# Labels #}
{% block form_label %}
{% spaceless %}
{% 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 %}
{% endif %}
{% if 'checkbox' not in block_prefixes %}
<label{% for attrname, attrvalue in label_attr %} {{ attrname }}="{{ attrvalue }}"{% endfor %}>{{ label|trans({}, translation_domain) }}</label>
{% endif %}
{% endspaceless %}
{% endblock form_label %}
{# Checkboxes #}
{% block button_label %}{% endblock %}
{% block checkbox_widget %}
{% spaceless %}
<label for="{{ id }}">
<input type="checkbox" {{ block('widget_attributes') }}{% if value is defined %} value="{{ value }}"{% endif %}{% if checked %} checked="checked"{% endif %} />
{{ label }}</label>
{% endspaceless %}
{% endblock checkbox_widget %}
它工作正常,但我无法让复选框的标签文本节点正常工作。
当我有一个复选框时,它会生成如下内容:
<label><input type="checkbox"/></label>
它应该在哪里:
<label><input type="checkbox"/>Label Here</label>
关于如何使标签字符串出现在复选框之后的任何线索?
编辑:
我找到了一个解决方案,效果很好,但我不确定它是否是最好的。
{% block form_row %}
{% spaceless %}
<div>
{{ form_errors(form) }}
{% if 'checkbox' in block_prefixes %}
{{ form_widget(form) }}
{{ form_label(form) }}
{% elseif 'radio' in block_prefixes %}
{{ form_widget(form) }}
{{ form_label(form) }}
{% else %}
{{ form_label(form) }}
{{ form_widget(form) }}
{% endif %}
</div>
{% endspaceless %}
{% endblock form_row %}
【问题讨论】:
-
您使用 block_prefixes 实现的代码是我正在寻找的。当标签用于复选框字段时,我需要提供一些样式。谢谢
标签: symfony checkbox label overriding twig