I am trying to render a template in Drupal 8. In Drupal 7, I would implement hook_theme()
, make a templates directory in my module, drop the template file in that directory, and I could display it with theme()
.
What's the equivalent in Drupal 8?
I tried the following code, but it doesn't work.
/**
* Implements hook_theme().
*/
function twitter_pull_theme($existing, $type, $theme, $path) {
return array(
'twitter_pull_tweet_listing' => array(
'variables' => array(
'description' => array(),
),
'template' => 'templates/twitter_pull_tweet_listing',
),
);
}
Inside the twitter_pull/templates directory, there is the twitter_pull_tweet_listing.html.twig template file.
This is the code used from the block.
$tweet_template = array('#theme' => 'twitter_pull_tweet_listing', '#attributes' => array('params' => $params));
$output = drupal_render($tweet_template, array('params' => $params));
print $output;
I get the following error in the log.
User error: "content" is an invalid render array key in Drupal\Core\Render\Element::children() (line 89 of C:\xampp\htdocs\drupal\core\lib\Drupal\Core\Render\Element.php).
Twig_Error_Loader: Unable to find template "modules/custom/twitter_pull/templates/templates/twitter_pull_tweet_listing.html.twig" (looked into: C:\xampp\htdocs\drupal). in Twig_Loader_Filesystem->findTemplate() (line 202 of C:\xampp\htdocs\drupal\core\vendor\twig\twig\lib\Twig\Loader\Filesystem.php).
I imagine this error is caused by not using namespaces and autoloading correctly.
I am not sure I put the template file in the correct directory. Based on the error message, I even tried to put it at C:\xampp\htdocs\drupal\templates\ but it still didn't work.
drupal_render()
? It's expecting a booleantemplates/templates/
part in the 2nd error message makes me think you should try'template' => 'twitter_pull_tweet_listing',
instead of'template' => 'templates/twitter_pull_tweet_listing',
inhook_theme()