forms - 标签选择表单中的 HTML

标签 forms symfony twig html-escape-characters

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

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

并在 twig 中渲染字段的函数:

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

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

最佳答案

您必须在自定义主题中自定义 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' %}

关于forms - 标签选择表单中的 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45562135/

相关文章:

c# - ASP.NET MVC 条件验证

symfony - render(controller()) 的替代品

html - CSS - 使用数据属性添加颜色 - attr(data-color color)

php - 如何在 Twig 中渲染 CSRF 输入?

numbers - 在 Twig 模板中格式化金钱

php - 在 Symfony 3 中为集合的每个元素应用特定的验证组

php - $_POST var 未填充,而是 $HTTP_RAW_POST_DATA 获取数据

jQuery 表单对齐插件?

php - 强制存储库返回 CustomClass 类型而不是 Object 类型

Symfony 2隐藏表单字段文本