How to define an array in a branch

I need to display an image in twig based on the value that comes from the controller. For example, in the image of the house, which should appear if the value coming from the controller (home or home, update or reconstruction or rental or rental), and the list goes on.

At the moment, what I am doing is as follows

 {% 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 it will get out of hand soon. Therefore, I thought just to create an array in the branch and check if the value coming from the controller exists on that array that I have on the branch to display the image.

+5
source share
1 answer

You can define an array with the syntax {key: value} or [value1, value2] . Read more about arrays and branches 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 %} 

You can also simplify the code to {% if goal|lower in keys %} and define the keys only in lower case, if you always need to check both cases.

+5
source

Source: https://habr.com/ru/post/1234576/


All Articles