Difference between extends and include using the SWIG Template Engine

Asked

Viewed 84 times

1

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

Could someone explain to me?

1 answer

0


Extends means that it picks up a piece of the template and complements it by inserting the code into each other in blocks/pre-created sites.

Includes means he takes a piece of the template and puts it into the code.

There are examples of both on Github (link), but I put here too:

Extend:

html layout.

<!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 opening index.html he will use the layout.html and extend/add the text Home Page within the block title that in the layout.html is with <title>{% block title %}{% endblock %} - Example</title>. In other words, it adds to the template.

Includes:

html form.

{% 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 contents. It inserts nothing inside that block, it simply imports it.

  • 1

    Show ball Sergio! I could understand better now the difference! Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.