2

私はdjangoで簡単なブログアプリを書いています。これに含まれているのは、ブログアプリのすべてのページで日付アーカイブとタグクラウドを利用できるようにしたいです。ただし、これはプロジェクトのすべてのページで必要なわけではありません。

コンテキストプロセッサを使用すると、プロジェクトのすべてのページでこれらを利用できるようになると思いますか?もしそうなら、これは私が必要としているものに対して少しやり過ぎのように思えます。ブログアプリに関係のないページでは、不要なクエリが実行され、追加のコンテキスト変数があります。これについてもっと良い方法はありますか?

4

2 に答える 2

2

タグクラウドなどの目的のコンポーネントを表示するカスタムテンプレートタグを作成します。参考 のためにマニュアルを参照してください。

from django import template
from django.template.loader import render_to_string

register = template.Library()

@register.simple_tag
def tag_cloud(): 

    tags = ['foo', 'bar']         # Fetch the tag cloud data here

    return render_to_string('tag_cloud_template.html', {'tags: tags})
于 2013-03-20T15:44:53.407 に答える
0

i see 2 solution: 1) inside a context processor, you can have the request object, so you can check if the url is in the blog apps. if you are in blog apps, you inject the desired data

2) you can make a context prosessor who inject a function who compute the desired data only at the template computing...

def mycontextpreprosessor(request):
    def my_func_who_work_hard():
        return range(10)

    return {"cloud",my_func_who_work_hard}

in this exemple, the range function will be called only if your template do

{{cloud}}

and will output

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
于 2013-03-20T15:46:03.837 に答える