N
N
Nick V2015-04-19 19:00:46
Django
Nick V, 2015-04-19 19:00:46

jinja2 template logic?

Good afternoon. Started learning Jinja2 templating engine. And I have some questions, namely:

  1. How to properly organize the logic of interaction between templates
  2. How to pass variable value from template to template

There are three files
  1. src/templates/base.html
  2. src/templates/index.html
  3. src/templates/layouts/header.html

src/templates/base.html

{% load staticfiles %}
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>{% block title %}{% endblock %}</title>
    <link rel="stylesheet" href="{% static 'css/reset.min.css' %}"/>
    <link rel="stylesheet" href="{% static 'css/main.css' %}"/>
</head>
<body>
    {% block header %}{% endblock %}
    {% block nav %}{% endblock %}
    {% block content %}{% endblock %}
    {% block footer %}{% endblock %}
</body>
</html>


src/templates/index.html

{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block header %}
{% include "layouts/header.html" %}
{% endblock %}


src/templates/layouts/header.html

<header>
    <p>{{ text }}</p>
</header>


The question is, am I doing it right? If not, please tell me how.
And how to pass the value {{ text }} from src/templates/layouts/header.html to src/templates/index.html

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nick V, 2015-04-20
@half-life

This is how it turns out to pass the value of a variable.

src/templates/base.html
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>{% block title %}{% endblock %}</title>
    <link rel="stylesheet" href="{% static 'css/reset.min.css' %}"/>
    <link rel="stylesheet" href="{% static 'css/main.css' %}"/>
</head>
<body>
    {% block header %}{% endblock %}
<script src="{% static 'js/main.js' %}"></script>
</body>
</html>

src/templates/index.html
{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block header %}
    {% with txt='1' %}
        {% include "layouts/header.html" %}
    {% endwith %}
{% endblock %}

src/templates/layouts/header.html
<header>
    <p>{{ txt }}</p>
</header>

src/templates/index.html
{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block header %}
    {% with txt='1' txt2='2' txt3='3' %}
        {% include "layouts/header.html" %}
    {% endwith %}
{% endblock %}

src/templates/layouts/header.html
<header>
    <p>{{ txt }}</p>
    <p>{{ txt2 }}</p>
    <p>{{ txt3 }}</p>
</header>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question