Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drupal 8 Passing Custom Variables to Theme Template

Tags:

drupal-8

So I have a controller with a route already configured my action looks like this

/**
 * List of brands
 *
 * @return array
 */
public function listAction()
{
    $brandIds = \Drupal::entityQuery('node')
        ->condition('type', 'brand')
        ->sort('title', 'asc')
        ->execute();

    return [
        'addition_arguments' => [
            '#theme' => 'page--brands',
            '#brands' => is_array($brandIds) ? Node::loadMultiple($brandIds) : [],
            '#brands_filter' => \Drupal::config('field.storage.node.field_brand_categories')->get()
        ]
    ];
}

I would like to use #brands and #brands_filter in my twig template theme file page--brands, but I never see it go through.

Can anyone help?

Thank you

UPDATE

Worked it out

In you modules my_module.module file add the following

function module_theme($existing, $type, $theme, $path)
{
    return [
        'module.brands' => [
            'template' => 'module/brands',
            'variables' => ['brands' => []],
        ],
    ];
}

In your controller use

return [
        '#theme' => 'mymodule.bands',
        '#brands' =>is_array($brandIds) ? Node::loadMultiple($brandIds) : []
]

This will inject the variable Hope this helps omeone else who has this problem, wish the docs were better :)

like image 612
Matthew A Thomas Avatar asked Aug 24 '16 10:08

Matthew A Thomas


1 Answers

Please refer below sample code :

mymodule.module

<?php

/**
 * @file
 * Twig template for render content
 */

function my_module_theme($existing, $type, $theme, $path) {
  return [
    'mypage_template' => [
      'variables' => ['brands' => NULL, 'brands_filter' => NULL],
    ],
  ];
}
?>

mycontorller.php

<?php
/**
 * @file 
 * This file use for access menu items  
 */
namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;

class pagecontroller extends ControllerBase {
        public function getContent() {
      return [
        '#theme' => 'mypage_template',        
        '#brands' => 'sampleBrand', 
        '#brands_filter' => 'sampleBrands_filter',       
      ];
  }
}

Twig File Name inside templates folder - mypage-template.html.twig

like image 179
Vernit Gupta Avatar answered Nov 04 '22 11:11

Vernit Gupta