A
A
Alexey Sergeev2015-04-09 14:43:47
Django
Alexey Sergeev, 2015-04-09 14:43:47

How to loop through multiple blocks in django templates?

Hello!
Please help, there is such a template
Basic template
content.html

<h3>{% block post_title %}Some title{% endblock %}</h3>
               <h4>{% block post_created_at %}Created by{% endblock %}</h4>
               {% block short_description %}Short Desctiprtion{% endblock %}
               {% block post_image %}Image{% endblock %}
               <a class="bttn" href="{% block post_detail_url %}{% endblock %}">MORE</a>

From it is inherited:
{% extends 'content.html' %}



{% for p in posts %}


{% block post_title %}{{ p.title }}{% endblock %}

{% block post_created_at %}Дата создания: {{ p.created_at }}. Создал: {{ p.author }} {% endblock %}

{% block short_description %} {{ p.short_description }} {% endblock %}

{% block post_image %}{{ p.post_image }}{% endblock %}

{% block post_detail_url %} {% url 'blog:detail' p.slug %} {% endblock %}
{% endfor %}

When you start the dev server, nothing is displayed. If you do it like this:
{% block post_title %} {% for p in posts %} {{ p.title }} {%endfor %} {% endblock %}

That works, but the solution is clearly not correct.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sim3x, 2015-04-09
@SergeevAI

You have a misunderstanding of inheritance in templates

Inherits from it:
{% extends '
that file is not inserted into content.html
It takes the content of content.html and replaces the content of the blocks
If you really need to repeat a piece of layout
{{ p.title }}
Дата создания: {{ p.created_at }}. Создал: 
.....

then include it in p.html use {% include "p.html" %} in content.html and other places
{% block post %}
{% for p in posts %}
   {% include "p.html" %}
{% endfor%}
{% endblock %}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question