In django, which should I generally prefer, and why?
-
long template variable names, passing as few “root objects” (e.g. request) as possible:
{% if request.current_page.get_children.0.get_absolute_url %} -
or pass a hell lot of different “root objects” and keep the template variable name simple:
{% if first_child_url %} -
somewhere in the middle, e.g. passing
children{% if children.0.get_absolute_url %}or passing
first_child{% if first_child.get_absolute_url %}
the advantage of the first approach is looser coupling, since I won’t need to change the view every time I need to use another variable; the advantage of the second approach is that the template is simpler and much cleaner.
If I’m using generic views (or third party views) which does not allow me to add additional context variables (therefore the only way to add context variables is by writing middleware or context processors), would that change anything?
There is no right answer for this, but I can give you something else to consider:
1) Mistyped variable names in a template will fail silently, which is why I normally try to avoid things like
2) In contrast to that, any issues in a view will immediately raise exceptions and be obvious to debug
3) What I sometimes do when the situation calls for it, is add shortcut methods to a model which allows me to call the method from the template but still keeping the complexity on the python side of the equation.
All that said, if you can’t add extra context and need to do it using template tags (as mentioned in your comments) I think its best if you go for the complicated template option.
I only use custom template tags when it is the only way to do something, never as a shortcut.
Hope this helps….