如何在树枝中定义数组
How to define an array in twig
我需要根据来自控制器的值在 twig
中显示图像。例如,如果来自控制器的值是(Home or home or renovation or Renovation or rent or Rent)并且列表还在继续,则应该出现在房屋图像中。
目前正在做的事情如下
{% if goal == "house" or goals == "House" or goal == "home" or goals == "Home" %}
<img src="{{ asset('bundles/bundlename/images/house.jpg') }}">
{% endif %}
列表很长,很快就会失控。所以我想简单地在树枝中创建一个数组,并检查来自控制器的值是否存在于我在树枝中显示图像的数组上。
您可以使用 {key: value}
或 [value1, value2]
语法定义数组。阅读更多关于数组和 twig 本身的信息 here。
您可以这样做:
{% set images = {
"house.jpg": ["house", "House", "home", "Home"]
... some more rules ...
} %}
{% for image, keys in images %}
{% if goal in keys %}
<img src="{{ asset('bundles/bundlename/images/' ~ image) }}">
{% endif %}
{% endfor %}
您还可以将代码简化为 {% if goal|lower in keys %}
,如果您始终需要检查两种情况,则只定义小写键。
在 twig 中定义数组
{% set section = { foo:{ heading:"bar" } } %}
{{ section.foo.heading }}
bar //output
{% set section = { foo:"bar" } } %}
{{ section.foo }}
bar //output
{% set section = { foo:"bar", one:"two" } } %}
{{ section.one }}
two //output
我需要根据来自控制器的值在 twig
中显示图像。例如,如果来自控制器的值是(Home or home or renovation or Renovation or rent or Rent)并且列表还在继续,则应该出现在房屋图像中。
目前正在做的事情如下
{% if goal == "house" or goals == "House" or goal == "home" or goals == "Home" %}
<img src="{{ asset('bundles/bundlename/images/house.jpg') }}">
{% endif %}
列表很长,很快就会失控。所以我想简单地在树枝中创建一个数组,并检查来自控制器的值是否存在于我在树枝中显示图像的数组上。
您可以使用 {key: value}
或 [value1, value2]
语法定义数组。阅读更多关于数组和 twig 本身的信息 here。
您可以这样做:
{% set images = {
"house.jpg": ["house", "House", "home", "Home"]
... some more rules ...
} %}
{% for image, keys in images %}
{% if goal in keys %}
<img src="{{ asset('bundles/bundlename/images/' ~ image) }}">
{% endif %}
{% endfor %}
您还可以将代码简化为 {% if goal|lower in keys %}
,如果您始终需要检查两种情况,则只定义小写键。
在 twig 中定义数组
{% set section = { foo:{ heading:"bar" } } %}
{{ section.foo.heading }}
bar //output
{% set section = { foo:"bar" } } %}
{{ section.foo }}
bar //output
{% set section = { foo:"bar", one:"two" } } %}
{{ section.one }}
two //output