Skip to content
Advertisement

Twig only showing first array level

My firstime ever asking a question in a forum. I normally use blade for templating but the standalone Twig is simpler to install. So I have this issue here i hope you can help me.

$breadcrums['titles'] = ['Home','Toys','Ball'];
$breadcrums['links'] = ['/','/toys','/toys/ball'];


{% for item in breadcrums %}

<a href={{ item.links }}> {{ item.titles }} </a>

{% endfor %}

I’am traying to achieve something like this, but the code prints nothing. In the other hand if a do this:

{% for value in breadcrums.titles %}
{{ value }}
{% endfor %}

works fine, but not what I’am trying to do. Thanks

Advertisement

Answer

I suggest you change your $breadcrumbs to

$breadcrumbs = [
    'Home' => '/',
    'Toys' => '/toys',
    'Ball' => '/toys/ball'
];

This makes your array more readable, you can easily see the title and its related link (instead of having two “unrelated” arrays).

In your twig template you can then use:

{% for title,link in breadcrumbs %}
<a href="{{ link }}">{{ title }}</a>
{% endfor %}

Solution for more attributes:

If you want to add more attributes to your breadcrumbs you can use something like:

$breadcrumbs = [
    [
        'title' => 'Home',
        'url' => '/',
        'atitle' => 'Link to the home page'
    ],
    [
        'title' => 'Toys',
        'url' => '/toys',
        'atitle' => 'Every toy you can imagine'
    ],
    [
        'title' => 'Ball',
        'url' => '/toys/ball',
        'atitle' => 'Ballroom blitz'
    ]
];

In your twig file you then use:

{% for breadcrumb in breadcrumbs %}
  <a href="{{ breadcrumb.url }}" title="{{ breadcrumb.atitle }}">{{ breadcrumb.title }}</a>
{% endfor %}

Will output:

<a href="/" title="Link to the home page">Home</a>
<a href="/toys" title="Every toy you can imagine">Toys</a>
<a href="/toys/ball" title="Ballroom blitz">Ball</a>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement