1

这是布局: 在此处输入图像描述 这是代码:

#base.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>{% block title %}{% endblock %}</title>
    </head>
    <body>
        <div id="content">
            <div id="l_col">
                {% block left %}{% endblock %}
            </div>
            <div id="r_col">
                {% block right %}{% endblock %}
            </div>
        </div>
    </body>
</html>
#views.py
def list( request ):
    vars = RequestContext( request, {
        'news': News.objects.all(),
        'top_news': News.news_manager.get_top_news()
    } )
    return render_to_response( 'news/list.html', vars )

def view( request, id ):
    vars = RequestContext( request, {
        'news': News.objects.filter( id = id ),
        'top_news': News.news_manager.get_top_news()
    } )
    return render_to_response( 'news/view.html', vars )
#news/list.html and news/view.html
{% extends 'base.html' %}
{% block left %}
    <!-- loop for news -->
{% endblock %}
{% block right %}
    <!-- loop for top news -->
{% endblock %}

如您所见,变量“top_news”在方法中重复:“list”、“view”和 2 个模板中的相同循环用于热门新闻
如何消除这种重复的代码?

4

2 回答 2

2

热门新闻的自定义模板标签。

于 2011-05-27T09:34:14.817 回答
2

我会写一个 template_tag 来处理 top_news。比您不必在视图中传递它们,而是在模板中您需要它的任何地方都包含它。

包含标签可能是最佳选择。

于 2011-05-27T09:36:03.923 回答