チェックボックスのラベルをより細かく制御できるように、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 %}