0

I have a custom module and placed comment.tpl.php here:

/sites/all/modules/mymodule/comment.tpl.php

But Drupal is not looking for that file in my custom module directory. How can i make it work?

2 Answers 2

5

You need to use hook_theme:

/**
 * Implements hook_theme().
 */
function MY_MODULE_theme($existing, $type, $theme, $path) {

  if($type != 'module') {
    return [];
  }

  // If you want to put your templates in a templates directory
  // in your module directory add .'/templates' to the end.
  $module_path = drupal_get_path('module', 'MY_MODULE');

  return [
    'comment' => [
      'template' => 'comment',
      'path'     => $module_path,
    ],
    'other_template' => [
      'template' => 'comment',
      'path'    => '/my/custom/path/here',
    ],
  ];
}

This has set up our custom theme, then when you want to use it you can:

$tpl_data = [
  'param1' => $foo,
  'param2' => $bar,
];

return theme('comment', $tpl_data);

Now $param1 and $param2 will be available in your template file too.

If you don't need any custom data in your template then $tpl_data can be omitted.

Happy days.

4
  • It worked! Thanks. If i want to use templates from a page,node i just have to change comment on page/node, right? Commented Mar 12, 2014 at 16:58
  • If you want to use another template file you can just add another line in your hook_theme function and supply the path to it (answer updated)
    – Felix Eve
    Commented Mar 12, 2014 at 17:01
  • I mean what if i want to use node.tpl.php in my module directory, sorry for such a silly questions :), oh i see now, So it would be 'node' => array('template' => 'node', $path) right? Commented Mar 12, 2014 at 17:04
  • Yes, that's right.
    – Felix Eve
    Commented Mar 17, 2014 at 8:55
0

You can do this by using hook_theme() as described on api.drupal.org. It allows you to register your module's theme implementation.

1
  • Can you throw an example please? Commented Mar 12, 2014 at 15:41

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.