Change the body class if page uses default.html.twig

Hi, I’m new to Grav and would like to assign the default.html.twig template a specific class.
Scenario: I am building a portfolio page that contains several pages, each of which are assigned different body classes in my CSS.


pages /

For the work page, I’ve created a work.html.twig template and a work-item.html.twig template.

When I click any item on the work page, it links to the single item and uses the default.html.twig template. I’m not sure how I can change it to something else.
I created different CSS classes for the body element in base.html.twig. I call them like so:

<body class="{{ page.title|lower|replace({' ': '-'}) }}">

This works for all pages. However, I want the single project item that uses default.html.twig to have a specific class of 'test' rather than the page title.

I feel like it’s something simple that I am overlooking. If you have any pointers, I’d greatly appreciate it. Thanks!

For now, I’ve changed my approach by adding a css_class to my .md files. This works well.

<body class="{{ page.header.css_class }}">

I’d still be interested to know if what I tried in my initial post can be done. Is there a way to grab the default.html.twig template and isolate it via a conditional statement or some such?

It sounds to me like you might be confused about how file names and template names work. What is the name of the .md file in work/single-project-folder-1 and its sibling? If you want to use one of those templates you created, the names need to be Also, where did you save those templates you created?

If you actually want that class in your default template, there are several ways. Many themes support a conventional custom header body_classes:

body_classes: test

If I want to be able to use CSS selectors in my theme that tell me the name of the template I’m using, I do something like this in my base template:

<body class="template-{{ page.template|trim }} {{ page.header.body_classes|e('html_attr') }}">

That would give me a body.template-default or whatever on every page.

Also, do you know about modifying themes and updating? Themes will be overwritten when you upgrade them, so it’s safer to either copy them or (better IMO) inherit them.

Thank you so much for your invaluable response! It was a naming error. I had used instead of for the corresponding Twig template which is why it resorted to the default.html.twig rather than the single-project.html.twig template.

Everything works as expected now.

Also, thank you for letting me know about future-proofing my template. I hadn’t gotten that far in the docs yet. Will set it up the way it is suggested.

Thanks again!

1 Like