-1

I have a custom module that I've defined a block with a template file.

In my modules .module file, I have a preprocess function...

/** * Implements hook_preprocess_short_login(). */ function mymodule_preprocess_short_login(&$variables) { // code }

My theme file is named short-login.html.twig

This does not work. With other templates and preprocess functions, I have always been able to name the function by replacing the hypen (-) with an underscore (_), but this did not work for my custom template file.

To test, I renamed the template file and all the places that call it.

/** * Implements hook_preprocess_shortlogin(). */ function mymodule_preprocess_shortlogin(&$variables) { // code }

Rename theme file... shortlogin.html.twig

This works and all my code executes. This is fine for a workaround, but I know there will be cases when I'd like to name my template files with more than one word.

  • 1
    mymodule_preprocess_short_login should work, as long as short_login is the theme hook. Can you show the code of hook_theme()? – 4k4 Aug 19 '17 at 16:43
  • function mytheme_theme($existing, $type, $theme, $path) { return [ 'short-login' => [//array of variables], ]; } – mlanning Aug 19 '17 at 16:47
  • 1
    Just replace - with _, anything other than alphanumeric and underscores are removed (which is why your 2nd attempt works) – Clive Aug 19 '17 at 16:49
  • 1
    in hook_theme you need to use underscores in the array key (which is btw. the theme hook) – 4k4 Aug 19 '17 at 16:49
  • It works. Thank you. Add this as an answer and I'll mark it. – mlanning Aug 19 '17 at 17:00
0

The naming schema of the preprocess hook hook_preprocess_HOOK() contains two HOOKs.

The first one at the beginning is a module/theme name and the second at the end is a theme hook, which is an array key of the template definition in hook_theme():

function hook_theme($existing, $type, $theme, $path) {
  return [
    'forum_display' => [
      'variables' => ['forums' => NULL, 'topics' => NULL, 'parents' => NULL, 'tid' => NULL, 'sortby' => NULL, 'forum_per_page' => NULL],
    ],
    'forum_list' => [
      'variables' => ['forums' => NULL, 'parents' => NULL, 'tid' => NULL],
    ],
    'forum_icon' => [
      'variables' => ['new_posts' => NULL, 'num_posts' => 0, 'comment_mode' => 0, 'sticky' => 0],
    ],
    'status_report' => [
      'render element' => 'requirements',
      'file' => 'system.admin.inc',
    ],
  ];
}

For the theme hook only alphanumeric and underscores are allowed.

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.