Drupal 8 theming basics

You can read below – kind of – a transcript of the presentation I gave at Drupal Developer Days, Szeged 2014.


Once upon a time

…there was a man who had to build a site for a client. This site was really a simple one: a contact form, a static page, articles, comments – and that’s all. And if you listen carefully you may realize that it sounds just like Drupal core! And because this story took place in December, last year, it could be not only Drupal 7, but Drupal 8! (We already had a nice alpha version at that time…)

To share some more details with you, the client was my wife and the developer was me. And I decided to use Drupal 8 because it was possible and I really wanted to learn about it. And I think the best way to learn new things is to face real challenges.

While the core functions of Drupal 8 were enough for us, we didn’t want to use core Bartik theme. We didn’t want to look like thousands of others sites on the net. We wanted something what is a little bit different. So I had to create something custom… And I did it.

Today I want to share some of my experiences with you from this process. I want to show you some examples that changed in theming when we use Drupal 8.

Create a sub-theme

I decided to create a sub-theme. So I looked fore a base theme. And I found one! I was so happy that I tweeted about it! To tell you the truth, it was the only one full Drupal 8 contrib theme at that time. It is called Gratis, made by Danny Englander. And I really like it!


The first step of creating a new theme is to provide all the information the system has to know about it. And we do it by creating a mysubtheme.info file. Well… we do it in this way in Drupal 7. However the thighs have changed in Drupal 8!

While Drupal 7 stores the configuration information in the database, Drupal 8 uses YAML configuration files for the same purpose. So Drupal 8 themes switched from .info files to .info.yml files. How does YAML look like?

Its syntax is similar to the .info files, but there are some differences. Instead of equals sign we have colon between key-value pairs. We use hashmark to mark comments and indentation to structure the file content (like the original syntax of Sass does it).



The required content of the file didn’t change radically. But there is a new required element. I had to tell to Drupal what kind of extension I provided to it. So I wrote “type: theme“. But we should write “type: module” if we provided a module or “type: profile” if we provided an installation profile.

Of course I had to define the human readable name and the Drupal core version of my sub-theme and becouse it’s a sub-theme I had to define the base theme (using the machine name of it).

It is good to know that while lots of the declarations in YAML use underscore in keys we still have to write “base theme” with a space between the words and we mustn’t use underscore.

Of course one can define additional information but they are not required and we don’t go into the details now.


So I notified Drupal about my sub-theme, but it didn’t do too much in this state. Just duplicated the look and feel of the base theme. So I had to declare the .css files what I used later to change the look of the site. This is the way we have to do it in Drupal YAML files. And you can see a new example of the YAML syntax: we use a hyphen and a space to define a list element.


As you know our theme inherits the stylesheets from the parent theme. They can be overridden or ignored but this facility in Drupal 7 is a little bit hacky and partially broken. That is why Drupal 8 introduces dedicated, separate properties in theme .info.yml file for adding, overriding, and removing stylesheets.


As you can see how much I talk about it you may realized that I like to deal with CSS-related things. So here is one more information about the topic (but the last, I promise). In Drupal 8 the CSS file structure is built following the SMACSS method, and selector declaration in the CSS files follows the BEM method. I won’t go in details but you can – and you should! – read more about it at Drupal.org in the CSS Coding Standards documentation. (Which means that we have CSS Coding Standards – did you know that?)


OK. That’s all about CSS. But I haven’t talked about that thing yet what we style with CSS. This is the HTML output of Drupal. Drupal 7 uses the PHPTemplate engine and .tpl.php template files to create this output.

But – because of more reasons – PHPTemlate is not the best option today. We had to look for a better solution. And…, Ladies and Gentleman…, we have it! We have Twig in core! And we are happy with that! Are you really happy?

But why should we be happy? Let me tell you some reasons.


Twig is a modern templating language and a template engine too. And it is secure. Using PHPTemplate you can delete records from the database or files from the file system by accident or of malice prepense. Using Twig you can’t do that. You haven’t got access to the database and to the file system.

Twig is fast. When your web page renders, the Twig engine takes the template and converts it into a ‘compiled’ PHP template which it stores in a protected directory. The compilation is done once. Then template files are cached.

Twig has a concise, tag-based syntax which is easy to learn. It is easy to understand and learn for not hardcode developers (site builders, CSS guys) too.


You can see a sample twig markup here. It is just an example but shows you some typical twig tags. They are all placed between curly brackets. And we have everything we need. We can print variables and elements of arrays or objects. We can add comments, define expressions like “if” conditions or “for” loops. And we also have the translate function which is a filter type in Twig.

The last example shows how we can work with HTML attributes. One can choose those which should be printed individually – like the class names in the example – and all the others* are printed afterwards by using the “attributes” variable. This is the standard method of the .html.twig templates of Drupal 8 core.
*UPDATE: “Attribute objects can now be printed multiple times, and printing out individual attributes (for example the class attribute) from the Attribute object no longer marks the individual attribute as printed. The Twig “without” filter can be used to prevent attributes from being printed. This change makes attributes within Twig templates behave the same as render arrays.” See the full change record.

It is important that you should only use a template, if you really need it. This means if you cannot modify the output using only CSS. This would be the case if you want to hide e.g. the secondary menu.

Tip: enable twig_debug in settings.php.

Advanced examples

I have some advanced theming examples for you and the first one is about template.php. In Drupal 8 it is renamed to a .theme file what should has the same name as the theme. Developers use this file to create custom functions or define custom variables. So it is still pure PHP code inside. Let me show you a quick example.


In Drupal 7, drupal_add_css(), drupal_add_js() and drupal_add_library() functions could be used to add JS and CSS to a page. In Drupal 8 you must use the #attached method in a render array instead. #attached was already available in Drupal 7, and was widely used, but now it’ll be the only way to attach assets.


My last example is the hook_library_info() function which can be used to load third party libraries. You may not used this too much, because Drupal 7 automatically loads the core libraries.

In Drupal 8 the function is replaced by the .libraries.yml configuration file. And the reason why you do have to know about it is that Drupal 8 does not load a lot of javascript by default for anonymous users. So you’ll need to use a mysubtheme.libraries.yml file to create some dependencies for loading things like jQuery.once or even drupal.js for that matter.

Resources for you

A short session is not enough to teach you all the new information. So if you want to know more you should do your homework yourself. Here are some resources which can help you.

I suggest you to read the change records which are very useful and contain a lot of information. We also have a growing Drupal 8 theming documentation at drupal.org. It is a good read too.

My first Drupal 8 site

I started my session with the story of the site which I built to my wife. Just with some CSS modifications and some small configuration changes I created a new theme based on Gratis.

Here it is: http://noi-kerekasztal.hu. I’m sure that I won’t win a design award with it – what is normal since I am not a designer – but there is no other site on the net which looks exactly the same. And that is enough for us.

(I didn’t include all the slides to this post, but you can find them at my speakerdeck.)

Megosztó személyiség vagy?

12 thoughts on “Drupal 8 theming basics

  1. I in the vein of the helpful info you provide in your articles. I’ll bookmark your blog and ensure once more at this time repeatedly. I’m wholly definite I will discover many original things non-discriminatory here! Good good fortune for the next!

  2. “So, the only “value” that continues to have any compelling reality for us is what’s written on a price tag.” No, thats bullshit, for me a price tag is something I do not care about, just a “(un)necessary evil”and I don’t believe, that a price tag plays any importance in your world !

  3. Los educadores tenemos algunas ideas para reducir las dramáticas cifras de abandono y fracaso escolar, y por lo tanto de mejorar los resultados educativos; hemos de dar un salto de calidad importante y debemos hacerlo todos juntos: enseñanza pública, concertada y privada. Lo de eliminar la financiación de bachillerato y Fp en concertada es un auténtico despropósito. Saludos.

  4. Здравствуйте! Я перепробовала много разных лекарств по улучшению ресниц. Эта проблема очень актуальна для меня. Потому что мои ресницы никогда не отличались красотой. Потому пробовала препараты, какие-то из них действительно улучшают на некоторое время. Но после покраски тушью или нанесения накладных ресниц они снова теряют длину, а хочется стойкого результата, чтобы результат был долгий. Чтобы может быть даже был лечебный эффект, а то чувствую, скоро мои редкие реснички совсем потускнеют. Покупала аптечные средства, результат – возврат к прежнему состоянию. Но совсем обойтись без туши, которая пагубно влияет на мои ресницы не могу. Что же делать? Как по кругу я хожу и не вижу подсказки. подскажите, пожалуйста, может вы знаете про какие –нибудь препараты, после которых мои ресницы приобретут длину. Ведь впереди лето, станут еще более блеклыми. Наверняка среди нас есть женщины с такими же проблемами, как вы решали эту проблему? Вот еще нашла этот сайт по ссылке http://intenselash.ru/?wmid=3031 , может кто-то уже пользовался, стоит ли такое использовать?

  5. Hello, Bryan! Thanks for getting back to me, and promptly, too! Do you know there are people I work with who never, ever return emails? Here you are, no obligations whatsoever, and writing back. Paul always hosts the good ones on his blog, and this is further proof! Thanks for the explanation. You have got me toying with other synonyms for ‘series’ that would be a thematic match for my horror/sci-fi WIP. Not ‘saga,’ but hmmmm…. this will be fun!Have a great weekend!

  6. Nos salvan estas reacciones espontáneas de pura humanidad. Claro que no podemos tomarnos la justicia por nuestra mano en un estado de derecho, pero… ¿quién ha dicho que exista estado de derecho en ciertos pueblos del Euskadi profundo? A las pruebas me remito. Exiliado. Así, sin más. Un beso!

Vélemény, hozzászólás?

Az email címet nem tesszük közzé. A kötelező mezőket * karakterrel jelöljük.