You are here

How to create custom twig templates from custom module

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.

style="display:block; text-align:center;"
data-ad-format="fluid"
data-ad-layout="in-article"
data-ad-client="ca-pub-3089600610336467"
data-ad-slot="5786342409">

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.

<p>Test twig template!</p>
 
<p>test_var: {{ test_var }}</p>

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.