【问题标题】:Symfony2 twig formsSymfony2 树枝形式
【发布时间】:2015-12-10 15:06:09
【问题描述】:

Symfony2 在渲染表单时使用了一些 twig 模板。 特别是,为了呈现折叠的 choice 表单字段,symfony2 使用以下 sn-p 代码(来自 form_div_layout.html.twig):

{%- block choice_widget_collapsed -%}
    {%- if required and placeholder is none and not placeholder_in_choices and not multiple -%}
        {% set required = false %}
    {%- endif -%}
    <select {{ block('widget_attributes') }}{% if multiple %} multiple="multiple"{% endif %}>
        {%- if placeholder is not none -%}
            <option value=""{% if required and value is empty %} selected="selected"{% endif %}>{{ placeholder != '' ? placeholder|trans({}, translation_domain) }}</option>
        {%- endif -%}
        {%- if preferred_choices|length > 0 -%}
            {% set options = preferred_choices %}
            {{- block('choice_widget_options') -}}
            {%- if choices|length > 0 and separator is not none -%}
                <option disabled="disabled">{{ separator }}</option>
            {%- endif -%}
        {%- endif -%}
        {%- set options = choices -%}
        {{- block('choice_widget_options') -}}
    </select>
{%- endblock choice_widget_collapsed -%}

在我的应用程序中,我想创建一个新的表单类型,它扩展了默认的折叠选项类型,但选项列表具有自定义格式。

换句话说,对于我的表单字段类型,名为 places_widget,扩展了 choice_widget_collapsed 块但重新定义了 choice_widget_options

我已经试过了:

/* My first attempt */
{%- block places_widget -%}
    {% block choice_widget_options %}
      {{ block('choice_places_widget_options') }}
    {% endblock choice_widget_options %}

    {{ block('choice_widget_collapsed') }}
{%- endblock places_widget -%}

/* My other attempt */
{%- block places_widget -%}
    {{ block('choice_widget_collapsed', { 'choice_widget_options' => choice_places_widget_options }) }}
{%- endblock places_widget -%}

/* together with */
{%- block choice_places_widget_options %}
    // code here
{%- endblock choice_places_widget_options -%}

这两种解决方案都不起作用,实际上我觉得我做事的方式不对。

有人知道如何实现目标吗? 提前谢谢你

【问题讨论】:

  • 你真的用 {%- -%} 作为标签吗?

标签: forms symfony twig


【解决方案1】:

可以使用主题自定义表单(请参阅此处的文档:http://symfony.com/doc/current/cookbook/form/form_customization.html#form-theming-in-twig

在您的情况下,您似乎需要加载自己的主题: {% form_theme form _self %}

请注意,您可以将这些块外部化到另一个文件中(请参阅http://symfony.com/doc/current/cookbook/form/form_customization.html#method-2-inside-a-separate-template 了解如何执行此操作)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-16
    • 2015-04-22
    • 1970-01-01
    • 2014-11-03
    • 2014-11-20
    • 1970-01-01
    相关资源
    最近更新 更多