[英]How to define an array in twig
I need to display an image in twig
based on a value that comes from controller.我需要根据来自控制器的值在
twig
显示图像。 For example there in an image of a home that should appear if the value coming from the controller is (Home or home or renovation or Renovation or rent or Rent) and the list goes on.例如,如果来自控制器的值是(家或家或装修或装修或装修或租金或租金)并且列表继续,则应出现在房屋图像中。
At the moment what is am doing is as following目前正在做的是如下
{% if goal == "house" or goals == "House" or goal == "home" or goals == "Home" %}
<img src="{{ asset('bundles/bundlename/images/house.jpg') }}">
{% endif %}
The list is pretty long and this is soon going to get out of hand.这份清单很长,很快就会失控。 So I was thinking to simply create an array in twig and check if the value coming from controller exist on that array i have in twig to display an image.
所以我想简单地在树枝中创建一个数组并检查来自控制器的值是否存在于我在树枝中显示图像的数组中。
You can define an array with {key: value}
or [value1, value2]
syntaxes.您可以使用
{key: value}
或[value1, value2]
语法定义数组。 Read more about arrays and twig itself here .在此处阅读有关数组和树枝本身的更多信息。
You can do something like:您可以执行以下操作:
{% 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 %}
Also you can simplify your code to {% if goal|lower in keys %}
and define keys only in lower case if you always have to check to both cases.您也可以将代码简化为
{% if goal|lower in keys %}
并且如果您总是必须检查这两种情况,则仅以小写形式定义键。
Defining an Array in 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.