【问题标题】:how to check in twig if a form field has label如果表单字段有标签,如何签入树枝
【发布时间】:2016-04-11 07:58:27
【问题描述】:

当通过迭代生成表单域时:

{% for field in form %}
{{ form_widget(field); }}
{% endform %}

然后它将封装一个 div 块围绕字段的输入类型,以及一个标签(如果它有标签)。

我想把它分成标签和小部件:

      <div class="form-group">                
        {% if field.vars.label is not null %}
          {{ form_label(field) }}
        {% endif %}
        {{ form_widget(field) }}
      </div>

但 field.vars.label 始终为空。顺便说一句,当我在没有条件的情况下生成时,它会正确显示标签。

如何获取标签的条件检查值?

提前谢谢你。

【问题讨论】:

  • 如果未设置 label,Twig 将使用 name。所以你的支票应该是{% if field.vars.label is not empty and field.vars.name is not empty %}。这看起来也像form customization cookbook 中描述的那样。
  • 你是对的。问题是,所有字段都有名称。我仍然不知道 form_widget 如何决定哪些字段有标签,哪些没有

标签: symfony twig symfony-forms


【解决方案1】:

将标签更改为 false,form_label() twig 函数会自动忽略它。

这是来自 form_div_layout.html.twig 文件的代码 sn-p(见第 2 行):

{%- block form_label -%}
    {% if label is not same as(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 -%}
            {%- if label_format is not empty -%}
                {% set label = label_format|replace({
                    '%name%': name,
                    '%id%': id,
                }) %}
            {%- else -%}
                {% set label = name|humanize %}
            {%- endif -%}
        {%- endif -%}
        <label{% for attrname, attrvalue in label_attr %} {{ attrname }}="{{ attrvalue }}"{% endfor %}>{{ translation_domain is same as(false) ? label : label|trans({}, translation_domain) }}</label>
    {%- endif -%}
{%- endblock form_label -%}

【讨论】:

  • 这让我做出妥协 :) 我想避免更改表单生成器,直到现在。谢谢,我应该接受这个解决方案
【解决方案2】:

根据表单变量参考的doc

尝试:

    {% if field.vars.attr.label is not null %}

代替:

    {% if field.vars.label is not null %}

【讨论】:

  • 对象“Symfony\Component\Form\FormView”的方法“标签”不存在。结果就是这样:(
  • @Roland 对不起,也可以试试field.attr.label
  • 再次抱歉@Roland,您应该通过field.vars.attr.label访问标签字段,而不是源代码。检查我的答案更新
  • Evgeny Soynov 是对的,这些字段没有标签,并使用“名称”,但尚不清楚 form_widget 如何决定哪些字段必须有标签,哪些没有
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-21
  • 1970-01-01
  • 2016-09-13
  • 2020-05-22
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
相关资源
最近更新 更多