You are here

public function TwigExtension::template in Components! 3.x

Same name and namespace in other branches
  1. 8.2 src/Template/TwigExtension.php \Drupal\components\Template\TwigExtension::template()

Includes the given template name or theme hook by returning a render array.

Instead of calling the "include" function with a specific Twig template, the "template" function will include the same Twig template, but after running Drupal's normal preprocess and theme suggestion functions.

Variables that you want to pass to the template should be given to the template function using named arguments. For example:


{% set list = template(
    "item-list.html.twig",
    title = "Animals not yet in Drupal core",
    items = ["lemur", "weasel", "honey badger"],
  )
%}

Note that template() returns a render array. This means you can filter it with Twig filters that expect arrays, e.g. `template(...)|merge(...)`. If you want to use a filter that expects strings, you can use Drupal's render filter first, e.g. `template(...)|render|stringFilter(...)`.

Instead of the template name, you can pass a theme hook name or theme suggestion to the first argument:


{% set list = template(
    "item_list__node",
    title = "Fictional animals not yet in Drupal core",
    items = ["domo", "ponycorn"],
  )
%}

Parameters

string|array $_name: The template name or theme hook to render. Optionally, an array of theme suggestions can be given.

array $variables: The variables to pass to the template.

Return value

array The render array for the given theme hook.

Throws

\Exception When template name is prefixed with a Twig namespace, e.g. "@classy/".

File

src/Template/TwigExtension.php, line 88

Class

TwigExtension
A class providing components' Twig extensions.

Namespace

Drupal\components\Template

Code

public function template($_name, array $variables = []) : array {
  assert(is_string($_name) || is_array($_name), 'The first argument must be a string containing the template name or theme hook to render or an array of theme suggestions.');
  if ($_name[0] === '@') {
    throw new \Exception('Templates with namespaces are not supported; "' . $_name . '" given.');
  }
  if (is_array($_name)) {
    $hook = $_name;
  }
  else {
    $hook = str_replace('.html.twig', '', strtr($_name, '-', '_'));
  }
  $render_array = [
    '#theme' => $hook,
  ];
  foreach ($variables as $key => $variable) {
    $render_array['#' . $key] = $variable;
  }
  return $render_array;
}