0

In my project, I have a " field--node--title.html.twig " file, I used this file to overwrite the title label to be able to give it a certain class.

I know you can be more specific using " field--node--title-x.html.twig ", Where x can be a block or a page!

I was wondering if there exists a better way of doing this. Maybe I could do IF conditions inside " field--node--title.html.twig " file to check for a certain block or a certain page.

This would be much easier and it would also decrease the number of files in the field folder in templates.

7
  • I don't think that it is possible
    – user72672
    Sep 20, 2017 at 15:38
  • Making logical decisions in templates is worse, not better. It means less can be cached.
    – Clive
    Sep 20, 2017 at 15:40
  • You can add your own twig suggestions too. Also, big no to doing a lot of logic in twig files.
    – Kevin
    Sep 20, 2017 at 15:54
  • @Clive, Kevin, you can implement logic in twig the same as in preprocess. Caching is the same for both. If you base the logic on information outside of the scope of the parent entity you have to include this in the cache metadata.
    – 4uk4
    Sep 20, 2017 at 18:15
  • @4k4 Caching aside, keeping display and logic separate has been a cornerstone of this kind of development for a long time. You definitely can keep your logic in a template, but best practice usually dictates that you don't. I haven't come across anything that suggests it would be different for Drupal
    – Clive
    Sep 20, 2017 at 18:46

1 Answer 1

1

Yes, usually there is a better way: preprocess functions allow you to alter the render array that is passed to the twig template. Adding a class is, in most cases, possible, but you might need to check how the twig file is turning the render array into markup.

This article has more info: https://www.drupal.org/docs/8/theming-drupal-8/modifying-attributes-in-a-theme-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.