Search code examples
htmltwigoctobercmscraftcms

How can I add a class, id or attribute to a twig include?


I am working on a project that uses twig. Each page uses

{% extends "_layouts/_master" %}

Inside the _layouts/master there is a body tag

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

Can I add a class to the body tag from a page that is using the include?


Solution

  • You can override parent block (defined in _layouts/_master) in child template (the one that extends parent). In your child template add this:

    {% extends "_layouts/_master" %}
    {% block bodyClass %}css-body-class another-css-body-class{% endblock %}
    

    You can also include content of parent block and append something to it:

    {% extends "_layouts/_master" %}
    {% block bodyClass %}{{parent()}} css-body-class another-css-body-class{% endblock %}
    

    You can read more in twig documentation for extends.