Difference between extends and include using the SWIG Template Engine

1

I'm using the Template Engine with NodeJS and I could not understand the difference between using extends and include. I was able to understand that the include you directly included a part of HTML anywhere, but I could not differentiate from the extends.

Could anyone explain?

    
asked by anonymous 20.09.2016 / 21:31

1 answer

0

Extends means that it fetches a piece of the template and complements it by inserting the code inside the other into pre-defined blocks / sites.

Includes means that it takes a piece of the template and places it inside the code.

There are examples of both in Github ( link ), but I also post here:

Extend:

layout.html

<!doctype html>
<html>
<head>
    <meta charset="utf-8" />
    <title>{% block title %}{% endblock %} - Example</title>


</head>
<body>

    <header>
        <h1>{% block title %}{% endblock %}</h1>
        {% block header %}{% endblock %}
        <nav>
            <ul>
                <li><a href="/">Home Page</a></li>
                <li><a href="/people">People</a></li>
            </ul>
        </nav>
    </header>

    <section role="main">
        {% block body %}{% endblock %}
    </section>

</body>
</html>

index.html

{% extends 'layout.html' %}

{% block title %}Home Page{% endblock %}

This example is very simple. When you open index.html it will use the layout.html template and extrude it / add the text Home Page within block title which in layout.html is with <title>{% block title %}{% endblock %} - Example</title> . In other words, it is added to the template.

Includes:

form.html

{% macro input(type, name, label) %}
<label for="{{ name }}">{{ label }}</label>
<input type="{{ type }}" name="{{ name }}" id="{{ name }}">
{% endmacro %}

{% macro button type label %}
<button type="{{ type|default("submit") }}">{{ label|default("Submit") }}</button>
{% endmacro %}

index.html

{% import 'form.html' as form %}

<ul>
    <li>{{ form.input("text", "name", "Your Name") }}</li>
    <li>{{ form.input("text", "age", "Your Age") }}</li>
</ul>

{{ form.button() }}

In this case index.html will fetch a new piece of code, including it in its content. It does not insert anything inside this block, it simply imports it.

    
20.09.2016 / 21:54