I am new to Drupal and I am trying to create a theme for it (Drupal 8). I have a few questions:

  1. What does it mean to pre-process a variable?
  2. Do all variables have to be pre-processed?
  3. How do you figure out how to pre-process a variable? I understand some come from the Drupal config. Where else can variables come from?

I have read a few articles and searched the Internet but it seems Drupal 8 documentation is still being worked on. It's not very explanatory. Are there any articles you can suggest to learn how to theme Drupal 8 from the ground up?

Thank you

  • Nothing has changed in this regard for Drupal 8. All is the same as in D7. – user21641 Jan 30 '16 at 8:36
  • 2
    @IvanJaros Considering that the question started with "I am new to Drupal", that's a pretty useless comment :) – Berdir Jan 30 '16 at 14:16

Preprocessing is just an optional step between defining a render array that will then use a twig template and the actual twig template.

It's a place where you can execute PHP code to prepare variables that you can later use in your template.

You don't have to use preprocess for you own templates but some things can only be done there or are a lot easier, as you can't execute arbitrary code in a twig template.

See template_preprocess_image() for an example. Note the different names of preprocess functions. There's always the one prefixed with template. That's reserved for the module that defines template in hook_theme() and is called first. And then it's called for each module and active theme, just like a hook, e.g. as yourmodule_preprocess_image.

That brings me to another advantage of the preprocess phase. There can only be one template that's actually used and while there are ways, modules in general shouldn't provide template unless they define it. But, every module can implement the preprocess function and influence the output of a template to a certain degree. For example to add a certain class or data attribute to a node so that some JS can then use it.

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.