I'm not sure that using the inclusion tag is actually your best bet ... There is no easy way, AFAIK, to dynamically invoke template tags from a template (and this is not the point of the template anyway :-)
I believe that I can make the following assumptions about your widgets, correct me if I am wrong:
- widget visualization function does not need parameters from the template context
- at best, he will need the current
request object (so that he can access user , session , etc.)
With this, you can think of your widgets as mini-views, returning a string instead of an answer:
def my_widget(request): ...
Now there are two questions for the address:
- How to get a dynamic list of all widget functions for all installed applications available in the template?
- How to call these widget functions in a template?
First point :
An easy way is to rely on an agreement. They have a uniform list of functions in the template_widgets.py module in all your applications, for example:
#
Then you can download the global list of widgets by looking at INSTALLED_APPS and automatically get it in all of your templates (using the context processor ). Of course, itβs better to load this list lazily so as not to waste processor cycles creating it if you are not going to use it.
#
Second point :
You now have a list of available widgets and are lazily loaded in each template. A convenient syntax for using it would be something like this:
## home.html ... <div id="widgets"> {% for widget in widgets %} <div class="widget"> {{ widget }} </div> {% endfor %} </div>
But this will not work, {[widget}} here called, which needs the request parameter. Djano does not allow you to make calls with parameters from the template, so you need to slightly change the context processor to return a list of (lazily) evaluated widget functions.
#
And now, the above template code should work.
Notes
- The order of the widgets in the list depends on the application orders in the
INSTALLED_APPS and in each widgets list. Itβs up to you to choose the right ordering method for you (for example, by weighing, using dict to access widget functions by name, etc.). - Remember to load the context processor and always use
RequestContext .
source share