Custom template files in Drupal 8 uses twig files. Apart from that defining a custom template is similar to Drupal 7. Custom templates are called and values are passed to custom template in the Controller classes in Drupal 8 module.
Define the custom template in the modulename.module file using hook_theme as in Drupal 7
function lncustomtemplates_theme($existing, $type, $theme, $path){ return array( 'my_template' => array( 'variables' => array( 'test_var' => NULL, ) ) ); }
Call the custom template and pass the variables to custom template in the Controller class.
namespace Drupal\lncustomtemplates\Controller; use Drupal\Core\Controller\ControllerBase; class CustomTemplatesController extends ControllerBase{ public function mytemplate(){ return array( '#theme' => 'my_template', '#test_var' => $this->t("This is a test value from custom template variable"), ); } }
Create a html.twig template file with the same name as custom template in the src/templates folder. Display the passed variables using {{ var }}
<h3>Custom Template File </h3> <strong> Test Var: </strong> {{ test_var }}
More information on custom templates can be found in Theme API in Drupal
Leave a Reply