1

What is the purpose of folders inside the templates folder in a theme? Where is specified that when rendering a page the template should be taken from layout/page.html.twig? Or a single node template from content/node.html.twig?

I could see content, block, field, form etc. in the /templates folder. I am referring to the Zymphonies theme. When I check Twig Template naming conventions I could see there are naming conventions for Twig templates. But what is the difference in giving Twig plain twig templates inside the templates folder and by giving specific twig templates in specific folders inside templates folder?

screen

1
  • 1
    I added the following sentence to drupal.org/docs/8/theming-drupal-8/…: You also can organize your templates in subfolders, for example all block templates inside templates/block and all views templates inside templates/views.
    – leymannx
    Dec 2, 2019 at 10:55

2 Answers 2

4

These folders are arbitrary. As long as the template is in the [THEME ROOT]/templates folder, it will be picked up. Using folders is simply the developer being well organized.

2
  • Meaning that we can give twig templates inside in any folder and Drupal will pick that?
    – KTM
    Dec 2, 2019 at 10:13
  • 2
    No it has to be in the templates folder or a sub folder.
    – Jaypan
    Dec 2, 2019 at 10:17
1

by default the [MY_THEME]/templates folder holding twig files is flattened, have a look at this folder /core/modules/system/templates. So, it's seen as a good practice to bring such organization to this folder and it's up to you to determine what logic suits your case. The twig engine is smart enough to pick up the right twig file.

Just to draw your attention when it comes to override an existing template, let say you want to override the default search form which uses this twig template /templates/forms/form.html.twig then you should create the template following this path /templates/forms/form--search-form.html.twig just to keep certain logic, but this doesn't prevent you to locate that file in an other folder or simply under /templates

you can also tell Drupal 8 where to find your new template using MY_THEME_theme hook :

function MY_THEME_theme($existing, $type, $theme, $path) {
  return [
    'search_form' => [
      'render element' => 'form',
      'template' => 'form/form--search-form',
    ],
  ];
}

don't forget to clear and rebuild cache to force twig engine to take in consideration your new twig file.

Your Answer

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

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