I have a JSON data file that is part of my application (version controlled, 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:
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.