For convenience it would be rather useful if there was a way for me to achieve the following inside my main layout template:

<body class="template--{{ getNameOfPageTemplateHere|replace({ '/':'-', '_':'' }) }}">

Such that a page rendered using the template "blog/_entry" would have the following body tag:

<body class="template--blog-entry">

Is this possible?

2 Answers 2


Maybe not the solution you was looking for, but here is an alternative solution I'm using.

Put a Twig block in your "master template" (_layout.html?) like this:

<body class="{% block bodyClass %}{% endblock bodyClass %}">

And from my templates I can add classes to the body tag like this:

{% block bodyClass %}{{ parent() }} news-index anotherclass{% endblock bodyClass %}

Or replace the classes by omitting the parent() like this:

{% block bodyClass %}news-index anotherclass{% endblock bodyClass %}
  • Thanks, but I already have something like this, I am using a variable rather than a block which gets set before @extends but I was hoping to avoid having to explicitly set the class for each of my templates, would have been nice if this could be automated.
    – Lea Hayes
    Dec 17, 2014 at 10:14

You can use {% set templateName = _self.getTemplateName() %} from _edit and pass that up as a variable that your layout template can utilize.

  • I have tried this but it does not seem to return the name of the template that is dealing with the request, but rather the name of the current template; '_layout.html' in my case.
    – Lea Hayes
    Dec 17, 2014 at 10:12
  • And you put the getTemplateName() call inside of the _edit template?
    – Brad Bell
    Dec 17, 2014 at 16:02

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.