3

I'm trying to do something you'd think was simple, but I don't find good documentation for it.

I'm trying to create a controller that displays a twig template.

I've done the following so far:

1) In my module directory, I've created a templates/ directory. It contains a field-permission-description.html.twig file, containing mostly HTML text. So far, I don't even have any {{ twig_variables }} in it:

<div class='examples-description>

  <p>Field permision text will be here.</p>

</div>

2) I have a theme function in my MY_MODULE.module file:

/**
 * Implementation of hook_theme
 *
 * Since we have a lot to explain, we're going to use Twig to do it.
 */
function MY_MODULE_theme($existing, $type, $theme, $path) {
    return [
      'field_permission_description' => [
        'variables' => [
          'stuff' => NULL
        ]
      ]
    ];  
}

3) In my controller, the function returning the render array looks like this:

  /**
   * A simple controller method to explain what this example is about.
   */
  public function description() {
    $build = [
      'description' => [
        '#theme' => 'field_permission_description',
        '#stuff' => 'some stuff',
      ]
    ];
    return $build;
  }

I clear the cache with drush, and go to the page. There's no error, even in the watchdog, but the content region of the description page is blank; the template does not render.

It's not a problem with the controller, since if I substitute something else (say, just a little HTML in a #markup key), it renders fine.

There's been a couple of answers a year or two ago, but these all have things that no longer work as of RC1.

What do I need to do to get a twig template to render the way I'm trying to do here?

2

The problem turns out to be a missing ' mark in the twig file itself.

It turns out that the twig was rendering, but since I had

<div class='examples-description>

and not

<div class='examples-description'>

the browser refused to show the badly written HTML.

So this was user error, but a hard user error to debug. I saw what was going on by looking at the source for the page, which made it obvious.

Hopefully this will save folks some trouble. But in any event: the technique I use here is valid, and works if you don't do stupid things in your twig :-)

  • Always use double quotes in html. – user21641 Oct 8 '15 at 16:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.