What I need is to automatically call a function (callback function) inside one or more views, get its result and pass it to the template.
Here’s a simplified example:
utils.py:
def getSContent():
return 'some dynamic data'
views.py:
def myFirstView(request):
...py code...
sData = getSContent() <== this line
return render_to_response('template.html',
{'sData': sData, <== this line
...
},
contenxt_instance = RequestContext(request))
def mySecondView(request):
...py code...
sData = getSContent() <== this line
return render_to_response('template.html',
{'sData': sData, <== this line
...
},
contenxt_instance = RequestContext(request))
..and so on.
sData = getSContent() and {'sData': sData} are repeated inside all these view functions.
- Is there any shortcut for this?
- Can I somehow bind this function to
specific views of my app without having to specify it (the marked
lines) all the time? - Can a decorator do this job?
Keep in mind that I need to catch the function’s return and pass it further to the template.
You can use TEMPLATE_CONTEXT_PROCESSORS setting for this
It’s a list of callables (functions). Each function receives
requestas an argument and should return adict, in your case –return {'sData': getSContent()}