How to create custom twig templates from custom module Drupal 8

Step #1: outline hook_theme in .module file
Create a [module].module file if it does not exist already, and add code that defines every of your twig templates.

function test_twig_theme($existing, $type, $theme, $path){return [ 'my_template' => [ 'variables' => ['test_var' => NULL], ], ]; }

Step #2: decision the model
In the place wherever you're returning your render array (whether from a controller technique that's known as from your router yml file, or wherever),build a decision to your twig model.

 

/** * @file * Contains \Drupal\test_twig\Controller\TestTwigController. */ namespace Drupal\test_twig\Controller; use Drupal\Core\Controller\ControllerBase; class TestTwigController extends ControllerBase { public function content(){return [ '#theme' => 'my_template', '#test_var' => $this->t('Test Value'),]; }}

 

Step #3: produce Twig model
In your module, inside the templates folder, produce your twig model. The name of the file should match what you set into hook_theme() (replace underscores with dashes). during this case, the file name would be my-template.html.twig.

Test twig template!

test_var: {{ test_var }}

The beauty of this is often that the model file outlined in your module are going to be used if such a file doesn't exist already in your theme. simply dump a file inside the /templates folder of your theme, clear cache (drush cr),and it'll scan that file instead. you'll be able to place the move into any nested sub-folder of the theme to stay things organized.

 

By: Mutasem Elayyoub