How to define an array in twig
Asked Answered
E

3

7

I need to display an image in twig based on a value that comes from controller. 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.

Emotion answered 27/10, 2015 at 6:15 Comment(0)
D
7

You can define an array with {key: value} or [value1, value2] syntaxes. 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.

Doradorado answered 27/10, 2015 at 7:6 Comment(1)
I think this is a good solution. I also recommend to add assetic image path definition in config.yml, so you can manage assets in the best way.Jacaranda
B
0

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
Bedpan answered 2/4, 2021 at 10:8 Comment(0)
G
0
{% set array = { 0:"gleneagles-experience", 1:"why-choose", 2:"partners", 3:"plan-travel", 4:"hospital-stay", 5:"going-home", 6:"helpful-resources" } %}

is equivalent to below array in php---

$array  = ["gleneagles-experience","why-choose","partners","plan-travel", "hospital-stay","going-home","helpful-resources"];
Ghiberti answered 28/6, 2023 at 19:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.