0

I want to build multidimensional array at Twig.

In php

 $attributes['attributes']['class'] = array();
 $attributes['attributes']['class'][] = 'innerTab';
 $attributes['html'] = TRUE;

Same thing I want to build in Twig. I tried but not getting proper one . Please check my code below

 {% set ctn = 0 %}
         {% for key, value in menu.menu %}
{% set attributes = {'attributes':'class'} %}
{% set attributes = attributes|merge( [ { (ctn) :'innerTab'} ,  {'html' : true} ]  ) %} 
{% set ctn = ctn+1  %}
 {% endfor %}

As a result I get :

array(3) { ["attributes"]=> string(5) "class" [0]=> array(1) { [0]=> string(8) "innerTab" } [1]=> array(1) { ["html"]=> bool(true) } } array(3) { ["attributes"]=> string(5) "class" [0]=> array(1) { [1]=> string(8) "innerTab" } [1]=> array(1) { ["html"]=> bool(true) } } array(3) { ["attributes"]=> string(5) "class" [0]=> array(1) { [2]=> string(8) "innerTab" } [1]=> array(1) { ["html"]=> bool(true) } }

  • 1
    I think it’s easier to create the array in a preprocess function and then loop through it in twig. – Jdrupal Jun 4 at 7:52
  • Yes, Twig is designed for objects, not for arrays and Drupal still has a lot of arrays. But this can be done in Twig, you only have to start backwards with the loop for the lowest level and then put the array together, because merge can only merge one level at a time. – 4k4 Jun 4 at 8:01
  • Although for attributes you can use an object now, see drupal.org/node/2818293 – 4k4 Jun 4 at 8:06
  • In Drupal 7 .. I used $menu_tabs .= l($title, $href, $attributes); to concatenate urls . But in drupal 8 inside twig I can't use {% set menu_tabs ~= link(title,support_url,attributes) %} . I also try with marge as link return array but not working.. Please help me – Arif Jun 4 at 9:50
  • The link() function accepts both, an attributes array or an Attribute object. – 4k4 Jun 4 at 10:17
0

In Drupal 8 use an Attribute object instead of a multidimensional array:

D7 PHP:

$attributes['attributes']['class'] = array();
$attributes['attributes']['class'][] = 'innerTab';

D8 Twig:

{% set attributes = create_attribute() %}
{% set attributes = attributes.addClass('innerTab') %}

You can use the Attribute object in Twig link():

{{ link(title, support_url, attributes) }}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.