开发者

code duplication

Here is the layout:

code duplication

Here is the code:

#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 %}

As you see variable 'top_news' repeats in methods: 'list', 'view' and in 2 templates same loop for top news

How to eliminate this duplication of code ?


I'd write a template_tag, that would handle the top_news. Than you won't have to pass them in the views, but include it everywhere you need it in the templates.

Inclusion Tags might be the best choice.


Custom template tag for top news.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜