I don't fully understand how preprocessing works

I have a twig template /themes/custom/client/templates/content/node--myfile.html.twig that I want to alter

I want to show/hide a part of that template depending on a field display with the machine name field_display stored in the matching content type called Project and with the machine name project_machine_name.

So I well understand I have to use hooks in order to do this, but I don't understand how I am supposed to name the hook functionnality neither how I'm supposed to access the data stored from the content type into the hook to alter the template view.

I know the hooks goes into the .module file. Actually I already have some of them, but I don't understand them properly. The only things I know for sure is that the function name must start by the module name

function my_module_SOMETHING_SOMETHINGELSE() {


So the issue is: how to name the hook function in order to alter the template ? I guess I understand the name is some kind of standard structure which will tell drupal if the function needs to be called before a specific action.

How to retrieve data stored from the display field of the content-types Project?

Thanks for your assistance.

1 Answer 1


Preprocess hooks are named MY_MODULE_preprocess_TEMPLATE_NAME, in your case:

function my_module_preprocess_node__myfile(&$variables) {}

Notice how I replace the template's dashes with underscores in the function name.

Now you can get the display variable from $variables['node']->field_display->value.

  • Thanks but I wonder if there isn't something to do in order to make the hook effective. I've just set a var_dump in the my_module_preprocess_node__myfile but nothing is triggered when I go to the page.
    – Minirock
    Nov 26, 2019 at 11:27
  • 2
    Have you cleared the cache?
    – user72672
    Nov 26, 2019 at 11:29
  • I didn't. It's fine now, thank you. I still need to look how i'm going to really alter the resulting html but that's an other issue.
    – Minirock
    Nov 26, 2019 at 11:34
  • Cool, glad it helped :)
    – user72672
    Nov 26, 2019 at 11:35

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.