node.jsexpressswig-template

How to use multiple partials with Swig?


Swig doesn't render some partials in my view. How to pass blocks the right way? What file should extend what?

I have such a structure of my view:

// files
header.html   // <- partial
header_logo.html   // <- partial
layout.html   // <- layout
index.html   // <- page

index.html is the one that Swig renders. It looks like this:

{% extends 'layout.html' %}
{% extends 'header.html' %}
{% extends 'header_logo.html' %}

{% block head %}
    {% parent %}
    <link href="/assets/css/index/index.css" rel="stylesheet">
{% endblock %}

{% block content %}

     {% block header_logo %}{% endblock %} // <- This one doesn't render

     .... html content code goes here ....
{% endblock %}

layout.html looks like this:

<!DOCTYPE html>
<html lang="en">
  <head>
    {% block head %}
        <link href="/assets/css/index/layout.css" rel="stylesheet">
    {% endblock %}
  </head>
  <body>

    {% block header %}{% endblock %}

    {% block content %}{% endblock %}  

  </body>
</html>

header.html looks like this:

{% extends 'layout.html' %}

{% block header %}
    ... html code goes here ...
{% endblock %}

header_logo.html looks like this. And this one doesn't render.

{% extends 'layout.html' %}

{% block header_logo %}
    ... html code goes here ...
{% endblock %}

Solution

  • You can only extend one template per file. What you want to do is something like this...

    Or, it looks like you want to include header_logo in your index.html template, not extend from it. You might be better off doing something like this...

    index.html

    {% extends 'layout.html' %}
    
    {% block header %}{% include 'header.html' %}{% end block %}
    {% block content %}
        {% include 'header_logo.html' %}
    ...
    {% endblock %}