簡體   English   中英

如何在樹枝中定義數組

[英]How to define an array in twig

我需要根據來自控制器的值在twig顯示圖像。 例如,如果來自控制器的值是(家或家或裝修或裝修或裝修或租金或租金)並且列表繼續,則應出現在房屋圖像中。

目前正在做的是如下

{% 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]語法定義數組。 在此處閱讀有關數組和樹枝本身的更多信息。

您可以執行以下操作:

{% 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 %}並且如果您總是必須檢查這兩種情況,則僅以小寫形式定義鍵。

在樹枝中定義數組

{% 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM