代码重复

时间:2011-05-27 09:30:55

标签: django code-duplication

这是布局: enter image description here 这是代码:

#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个模板相同的循环以获得最新消息
如何消除这种重复的代码?

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

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

Inclusion Tags可能是最佳选择。

相关问题