I've decided to include opportunities of the bootstrap library in drupal native forum and I'm trying to add new class into a nested array in twig. Here is my code.

{%  set topics['#rows'][0][0]['class'] = topics['#rows'][0][0]['class']|merge(['col-xs-9', 'col-sm-6']) %}
{%  set topics['#rows'][0][1]['class'] = topics['#rows'][0][1]['class']|merge(['col-xs-3', 'col-sm-2']) %}
{%  set topics['#rows'][0][2]['class'] = topics['#rows'][0][2]['class']|merge(['hidden-xs', 'col-sm-4']) %}

But upon executing the page an error is being displayed. Here is description of the error.

Twig_Error_Syntax: Unexpected token "punctuation" of value "[" ("end of statement block" expected). в Twig_TokenStream->expect()

Could you clarify me, how to properly add new elements into the compound array ?

  • hook_preprocess
    – user21641
    Commented Jun 11, 2017 at 14:10
  • this is a good suggestion from @IvanJaros, twig doesn't have the tools to manipulate nested arrays and you need to do this in php, for example in a preprocess hook or a twig extension
    – 4uk4
    Commented Jun 11, 2017 at 16:36
  • I have tried to use preprocess function, i.e. mytheme_preprocess_table__forum_topic_list(&$vars), but I can't catch sight of the array field where attribules are located. Commented Jun 11, 2017 at 16:57

1 Answer 1


I managed to solve the problem via hook_preprocess. Here's the code

function mytheme_preprocess_table__forum_topic_list(&$vars){
    $vars['header'][0]['attributes']->addClass(['col-xs-9', 'col-sm-6']);
    $vars['header'][1]['attributes']->addClass(['col-xs-3', 'col-sm-2']);
    $vars['header'][2]['attributes']->addClass(['hidden-xs', 'col-sm-4']);

    $vars['rows'][0]['cells'][0]['attributes']->addClass(['col-xs-9', 'col-sm-6']);
    $vars['rows'][0]['cells'][1]['attributes']->addClass(['col-xs-3', 'col-sm-2']);
    $vars['rows'][0]['cells'][2]['attributes']->addClass(['hidden-xs', 'col-sm-4']);
  • Another solution you can use module Twig DomQuery. It allow you can change html like 'jQuery' with Twig.
    – flashvnn
    Commented Mar 10, 2020 at 4:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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