如何在Twig中定义数组

7
我需要根据控制器传来的值在twig中展示一张图片。例如,如果从控制器传来的值是(Home或home或renovation或Renovation或rent或Rent),则应该显示一个家的图像,等等。
目前我所做的是:
{% if goal == "house" or  goals == "House" or goal == "home" or  goals == "Home" %}
<img src="{{ asset('bundles/bundlename/images/house.jpg') }}">
{% endif %}

这个列表相当长,很快就会失控。所以我在想,是否可以在Twig中创建一个数组,检查从控制器传来的值是否存在于我在Twig中拥有的数组中,以显示一张图片。

3个回答

7

你可以使用{key: value}或者[value1, value2]的语法来定义数组。关于数组和Twig本身的更多信息,请在此处阅读。

你可以像下面这样做:

{% 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 %},如果您总是需要检查两种情况,请将键定义为小写字母。

1
我认为这是一个好的解决方案。我还建议在 config.yml 中添加 assetic 图像路径定义,这样您可以以最佳方式管理资源。 - sentenza

0
{% set array = { 0:"gleneagles-experience", 1:"why-choose", 2:"partners", 3:"plan-travel", 4:"hospital-stay", 5:"going-home", 6:"helpful-resources" } %}

在PHP中等同于下面的数组---

$array  = ["gleneagles-experience","why-choose","partners","plan-travel", "hospital-stay","going-home","helpful-resources"];

0

在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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接