Components (or partials) are stored inside the components folder. Like layout files, components are written in Nunjucks. You can include any component from any layout (or another component) by using Nunjucks include tag:

{% include "footer.html" %}

Required Components

Two component file names are required for customizing the internal base.html layout.

  • html_head.html - content that will be placed inside the <head> tag
  • post_body.html - the content of this component will be included at the bottom of the <body> tag. Although same behaviour could be achieved by adding content at the bottom of body.html, there is a subtle difference. Content added in post_body.html will be rendered as SSR when running gatsby develop

These components are required by the base.html which is an internal Unibit file and has the following structure:

// base.html

<!doctype html>
<html>
    <head>
        {% include "html_head.html" %}
    </head>
    <body>
        {% block body %}{% endblock %}
        {% include "post_body.html" %}
    </body>
</html>

Passing Include Variables

Nunjucks include tag passes current context to the included component.

{% set hello = "world" %}
{% include "component.html" %}

components/component.html

{{ hello }} {# prints "world" #}

While this will always work in Nunjucks, when converting a theme to another SSG, it will not work in some cases:

  • The passed variables are not site or page
  • The include tag is inside for tag

In these cases an extra step is required:

{% set include_dict = {"hello": "hello"} %}
{% include "component.html" %}

components/component.html

{{ include_dict.hello }}

Following naming rules must be used when passing special objects:

  • key must be site when, and only when, passing the global site object
  • key must be page when, and only when, passing the global page object
  • key must be <name>_page when, and only when, passing page object other than global page object
  • key must be <name>_pages when, and only when, passing list of page objects
  • key must be paginator when, and only when, passing the paginator object
  • key must be menu when, and only when, passing a menu object from site.menus.<menu_name> or a site.menus.<menu_name>[index].children object

To simplify themes development, we are working on extending Nunjucks to allow includes with scoped arguments:

{% set hello = "world" %}
{% include "component.html" includes = {hello: hello, page: page} %}

components/component.html

{{ includes.hello }} {# prints "world" #}