【问题标题】:Passing Twig variables from array into an include将 Twig 变量从数组传递到包含
【发布时间】:2016-07-07 14:16:18
【问题描述】:

我有一个要迭代的数组以将不同类型的组件拉入我的页面:

array(
    'content'=> array(
        'componentA'=>array(
            'val'=>'1',
            'title'=>'sample title'
        ),
        'componentB'
    )
)

我正在尝试将变量从数组传递到包含的模板,但我不确定如何将连接生成的字符串转换为包含可以理解为变量数组的内容。当我从第一个 @components 包含中排除“with”时,它会打印出我在可迭代组件中设置的所有默认值,就像我期望的那样,但是当我保留 with 属性时仍然给我一个白屏。当我显示 var 本身,它返回这个字符串: (注意,我也尝试在 {{k}} 周围加上引号,但无济于事)

{ val:'1',title:'sample title' }

如何将数组中的变量传递给组件?

{% for key,item in content %}
    {% if item is iterable %}

        {% set var = [] %}
        {% for k,v in item %}
            {% set temp %}{% if loop.first %} { {% endif %}{{ k }}:'{{ v }}'{% if loop.last %} } {% endif %}{% endset %}
            {% set var = var|merge([ temp ]) %}
        {% endfor %}
        {% set var = var|join(',') %}

        {{ include ("@components/" ~ key ~ ".tmpl",var) }}
    {% else %}
        {{ include ("@components/" ~ item ~ ".tmpl") }}
    {% endif %}
{% endfor %}

【问题讨论】:

    标签: twig


    【解决方案1】:

    您的包含语句不正确。你使用的是{{ include ... }},应该是{% include ... %}

    如果您只想提供数组中的数据(而不是循环数据),则以下 sn-p 应该可以工作:

    {% for key,item in content %}
        {% if item is iterable %}
            {% include ("@components/" ~ key ~ ".tmpl") with item %}
        {% else %}
            {% include ("@components/" ~ item ~ ".tmpl") %}
        {% endif %}
    {% endfor %}
    

    然后您可以在组件模板中使用{{ val }}{{ title }}

    如果要包含循环数据,可以使用:

    {% for key,item in content %}
        {% if item is iterable %}
            {% include ("@components/" ~ key ~ ".tmpl") with {item: item, loop: loop} %}
        {% else %}
            {% include ("@components/" ~ item ~ ".tmpl") %}
        {% endif %}
    {% endfor %}
    

    然后您可以在组件模板中使用{{ item.val }}{{ item.title }}{{ loop.index }}

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-21
      • 2023-03-19
      • 2016-04-10
      • 1970-01-01
      • 2017-09-23
      • 2011-07-29
      • 1970-01-01
      • 2019-04-03
      相关资源
      最近更新 更多