这是我的模板代码:
{% 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 %}
在content block
for loop
确实有效,但在sidebar block
我无法使用变量latest_posts
。任何人都可以帮我这个吗?
答案 0 :(得分:4)
变量的范围仅限于包含{% block content %}
。您可以在{% block sidebar %}
内重复声明,也可以将其向上移动一级,使其超出{% block content %}
。
{% 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 %}
{% 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 %}
答案 1 :(得分:1)
您可以使用with
声明:
定义:
使用更简单的名称缓存复杂变量。这很有用 当访问“昂贵”的方法时(例如,一个击中的方法) 数据库)多次。
将现有块包装到此with子句中,您可以保护自己一些查询。它也应该解决你的问题:-)只需删除{% get_latest as latest_posts %}
行
{% 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 %}