Mirza Delic
Mirza Delic

Reputation: 4339

Django template using variable in two blocks

This is my template code:

{% block content %}
    {% get_latest as latest_posts %}
    <ul>
    {% for post in latest_posts %}
        <li>
            <p><a href="{{ post.get_absolute_url }}">{{ post.title|safe }}</a></p>
        </li>
    {% endfor %}
    </ul>
{% endblock %}

{% block sidebar %}    
    <ul>
    {% for post in latest_posts %}
        <li>
            <p><a href="{{ post.get_absolute_url }}">{{ post.title|safe }}</a></p>
        </li>
    {% endfor %}
    </ul>
{% endblock %}

In the content block the for loop does works, but in the sidebar block I can't use the variable latest_posts. Can anyone help me with this?

Upvotes: 0

Views: 680

Answers (2)

Dr.Elch
Dr.Elch

Reputation: 2225

You can use the with statement:

Definition:

with Caches a complex variable under a simpler name. This is useful when accessing an “expensive” method (e.g., one that hits the database) multiple times.

Wrap your existing block into this with clause and you can safe yourself some queries. also it should solve your problem :-) Just remove the {% get_latest as latest_posts %} line

{% with latest_posts=get_latest %}

{% block content %}
    <ul>
    {% for post in latest_posts %}
        <li>
            <p><a href="{{ post.get_absolute_url }}">{{ post.title|safe }}</a></p>
        </li>
    {% endfor %}
    </ul>
{% endblock %}

{% block sidebar %}    
    <ul>
    {% for post in latest_posts %}
        <li>
            <p><a href="{{ post.get_absolute_url }}">{{ post.title|safe }}</a></p>
        </li>
    {% endfor %}
    </ul>
{% endblock %}
{% endwith %}

Upvotes: 2

John Kugelman
John Kugelman

Reputation: 361585

The variable's scope is limited to the containing {% block content %}. You can either repeat the declaration inside {% block sidebar %}, or move it up a level so it's outside of {% block content %}.

example

{% get_latest as latest_posts %}

{% block content %}
    <ul>
    {% for post in latest_posts %}
        <li>
            <p><a href="{{ post.get_absolute_url }}">{{ post.title|safe }}</a></p>
        </li>
    {% endfor %}
    </ul>
{% endblock %}

{% block sidebar %}    
    <ul>
    {% for post in latest_posts %}
        <li>
            <p><a href="{{ post.get_absolute_url }}">{{ post.title|safe }}</a></p>
        </li>
    {% endfor %}
    </ul>
{% endblock %}

or

{% block content %}
    {% get_latest as latest_posts %}
    <ul>
    {% for post in latest_posts %}
        <li>
            <p><a href="{{ post.get_absolute_url }}">{{ post.title|safe }}</a></p>
        </li>
    {% endfor %}
    </ul>
{% endblock %}

{% block sidebar %}  
    {% get_latest as latest_posts %}  
    <ul>
    {% for post in latest_posts %}
        <li>
            <p><a href="{{ post.get_absolute_url }}">{{ post.title|safe }}</a></p>
        </li>
    {% endfor %}
    </ul>
{% endblock %}

Upvotes: 4

Related Questions