1

I have followed the guide at http://befused.com/drupal/first-drupal8-module to create a simple Drupal 8 controller, and it works as described. Instead of printing "Hello World" I would like to create more complex HTML. I found a guide that appears to step through what I need to do at http://jonathanpatrick.me/blog/safe-markup. I added hook_theme to my flot_d8.module file:

function flot_d8_theme(array $existing, $type, $theme, $path) {
  return array(
    'flot_d8_my_template' => array(
      'template' => 'my-template',
      'variables' => array(
        'variable1' => NULL,
        'variable2' => NULL,
      ),
    ),
  );
}

and created the my-template.html.twig file exactly as shown:

<div class="my-template">
  This is the first variable: <b>{{ variable1 }}</b>.
  This is the second variable: <i>{{ variable2 }}</i>.
</div>

I'm guessing my problem is in the way I try to call the theme. My controller code is:

namespace Drupal\flot_d8\Controller;
use Drupal\Core\Controller\ControllerBase;
class Flot_d8 extends ControllerBase {
  public function content() {
    return [
      '#theme' => 'flot_d8_my_template',
      '#variable1' => t("First"),
      '#variable2' => t("Second"),
    ];
  }
}

Is this the correct way to print a <div> to the screen? Do I need to register the template file in my info file somewhere?

2
  • 1
    This may help drupal.stackexchange.com/questions/136139/…
    – mona lisa
    Commented Dec 14, 2015 at 18:51
  • You do not need to declare template in hook_theme, that is the default value now(instead of render element). Also your template should be flot-d8-my-template.html.twig, and it has to be placed in templates directory in your module. Other than that clearing cache should be all that is needed since all looks good.
    – user21641
    Commented Dec 14, 2015 at 18:57

1 Answer 1

2

I removed the template line from hook_theme and renamed the file to flot-d8-my-template. Cleared the cache and it worked.

1
  • 2
    Please don't add "thanks" as answers. Invest some time in the site and you will gain sufficient privileges to upvote answers you like, which is the Drupal Answers way of saying thank you.
    – mpdonadio
    Commented Dec 14, 2015 at 19:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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