开发者

Passing static JSON to Django Template - best practices?

I have a JSON data file that is part of my application (version controlled,开发者_JAVA技巧 etc.), and several of our templates need the data in this file to render properly.

What are the pros and cons of various ways of making this JSON data available to the templates?

Let's start with the fairly simple option of storing the JSON data as a template, asking the template renderer to generate it, parsing that as JSON, and passing that as a template context param for each view that needs it:

'mydata': simplejson.loads(render_to_string('data/mydata.json'))

(This seems somewhat wasteful of CPU cycles and possibly disk access. Would the rendered JSON "template" at least be cached automatically?)

What are some other options? Is there any built-in feature of Django I'm missing that's designed for this type of use case?


The simplest and probably fastest thing to do is to just parse the json in your views.py outside of the actual view:

mydata = simplejson.loads(json_file)

def foo(request):
    ...
    return render(request, 'template.html', {"mydata": mydata},
        content_type="application/xhtml+xml")

The json will only be parsed the first time a view from the views.py file is requested, subsequent requests will not cause it to be parsed again. You could alternately use a context processor, as suggested.


If the data should be available on many/all pages, than a context_processor might be your best solution: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATE_CONTEXT_PROCESSORS

If you only need it on a couple of specific pages, than you can simply pass it to the template like you are doing now or make a template tag out of it.

As for saving cpu time, if you store it in a threadlocal variable than you don't have to parse it every time.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜