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

top_news を処理する template_tag を書きます。ビューでそれらを渡す必要はありませんが、テンプレートで必要なすべての場所に含めます。

包含タグが最良の選択かもしれません。

于 2011-05-27T09:36:03.923 に答える