【问题标题】:Html in label choice form标签选择形式的 HTML
【发布时间】:2017-08-08 07:39:10
【问题描述】:

choiceType 字段中我有参数 - 选择标签

   'choice_label' => function ($pay, $key, $index) {
        return "<b>".$pay->getName()."</b><br />";
    },

以及twig中字段的渲染功能:

{{form_widget(field)}}
{{form_errors(field)}}

当然我想用粗体字渲染getName, 我尝试使用树枝 autoescape{{form_widget(field)|raw}} - 没有成功

【问题讨论】:

  • 试试return new \Twig_Markup("&lt;b&gt;".$pay-&gt;getName()."&lt;/b&gt;&lt;br /&gt;", "UTF-8");
  • @DarkBee 不起作用
  • 浏览器不支持&lt;option&gt; 内容的AFAIK html 标记。尝试使用 css 样式。
  • 不是&lt;option&gt; 我将choiceType 渲染为单选按钮,所以choice_label&lt;label&gt;

标签: forms symfony twig html-escape-characters


【解决方案1】:

您必须在自定义主题中自定义choice_label 表单(例如:radioHTML.html.twig)=> 我只是将|raw 添加到标签文本中

{%- 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 -%}
    <{{ element|default('label') }}{% if label_attr %}{% with { attr: label_attr } %}{{ block('attributes') }}{% endwith %}{% endif %}>
    {%- if translation_domain is same as(false) -%}
        {{- label|raw -}}
    {%- else -%}
        {{- label|trans({}, translation_domain)|raw -}}
    {%- endif -%}
    </{{ element|default('label') }}>
{%- endif -%}
{%- endblock form_label -%}

您的表单类型只在choice_label 选项中返回html 字符串:

 $builder->add('fieldName', EntityType::class, array(
            'required' => true,
            'class' => 'AppBundle\EntityName',
            'choice_label' => function (EntityName $entity) {
                $html = '<div>';
                $html .= $entity->getName();
                $html .= '</div>';
                return $html;
            },
            'data' => null,
            'multiple' => false,
            'expanded' => true)

然后将它用于您的特定领域,例如在您的 twig TPL 中:

{% form_theme from.fieldNalme 'form/radioHTML.html.twig' %}

【讨论】:

    猜你喜欢
    • 2023-02-22
    • 1970-01-01
    • 2017-06-28
    • 2016-02-18
    • 1970-01-01
    • 1970-01-01
    • 2019-05-18
    • 1970-01-01
    • 2021-11-01
    相关资源
    最近更新 更多