重写复选框表单字段会产生重复标签并且在 Symfony 4.4 中没有字段

问题描述 投票:0回答:2

我在覆盖 Twig 模板内 Symfony 表单中的复选框字段时遇到问题。

我正在 Twig 模板中使用以下代码构建该字段:

{{ form_row(form.legal, {
   'label' : 'personal.form.fields.legal'|trans,
}) }}

在同一个模板中,我有以下块,我试图在其中自定义标签。请注意,上面的翻译包含 HTML,这就是我需要

raw
过滤器的原因。

{% block _crmpiccobundle_details_legal_label %}
    {% apply spaceless %}
        <label{% with { attr: label_attr } %}{{ block('attributes') }}{% endwith %}>
            {{ label|unescape|raw }}
        </label>
    {% endapply %}
{%- endblock %}

不幸的是,这不起作用,奇怪的是我留下了没有复选框和重复的标签,我不知道为什么。

symfony twig php-7.4 symfony-4.4 twig-filter
2个回答
0
投票

看起来您正在使用基于 bootstrap 的表单主题(如 bootstrap_4_layout.html.twig 或 bootstrap_3_layout.html.twig)

尝试这样做:

{% block _crmpiccobundle_details_legal_label %}
    {%- if widget is defined -%}
        {{ widget|raw }}
        
        {% apply spaceless %}
            <label{% with { attr: label_attr } %}{{ block('attributes') }}{% endwith %}>
                {{ label|unescape|raw }}
            </label>
        {% endapply %}
        
    {%- endif -%}
{%- endblock %}

在引导布局中,小部件部分需要包装到标签中,因此主题调用同一个块两次,第一次是

_label
部分,第二次是
_widget
部分。对于第二次调用,主题提供了
widget
变量,您必须自己渲染该变量(否则您将看不到复选框)。另外,您必须禁止标签渲染两次,这可以通过检查小部件是否已定义来完成。

看看原始块如何检查是否

widget is defined
以避免双标签渲染:

https://github.com/symfony/symfony/blob/e2f430dfb4c0c8cdde01ed111f4f0851e268ab5a/src/Symfony/Bridge/Twig/Resources/views/Form/bootstrap_3_layout.html.twig#L83


0
投票

我在

boostrap_5_layout
找到了同样问题的解决方案。

如果你不在顶部调用

{% use "bootstrap_base_layout.html.twig" %}
,它会给你一个双标签和一个双div.form-check。

所以只要像这样添加就可以了。

{% use "bootstrap_5_layout.html.twig" %}
{% use "bootstrap_base_layout.html.twig" %}

{%- block checkbox_widget -%}
    {%- set attr_class = attr_class|default(attr.class|default('')) -%}
    {%- set row_class = '' -%}
    {%- if 'btn-check' not in attr_class -%}
        {%- set attr_class = attr_class ~ ' form-check-input' -%}
        {%- set row_class = 'form-check' -%}
    {%- endif -%}
    {%- set attr = attr|merge({class: attr_class|trim}) -%}
    {%- set parent_label_class = parent_label_class|default(label_attr.class|default('')) -%}
    {%- if 'checkbox-inline' in parent_label_class %}
        {%- set row_class = row_class ~ ' form-check-inline' -%}
    {% endif -%}
    {%- if 'checkbox-switch' in parent_label_class %}
        {%- set row_class = row_class ~ ' form-switch' -%}
    {% endif -%}
    {%- if row_class is not empty -%}
        <div class="{{ row_class }}">
    {%- endif -%}
    {{- form_label(form, null, { widget: parent() }) -}}
    {%- if row_class is not empty -%}
        </div>
    {%- endif -%}
{%- endblock checkbox_widget %}
© www.soinside.com 2019 - 2024. All rights reserved.