开发者

Django: Should I have complex template variable names or complex views

开发者 https://www.devze.com 2023-03-23 17:14 出处:网络
In django, which should I generally prefer, and why? long template variable names, passing as few \"root objects\" (e.g. request) as possible:

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 开发者_如何学Pythonfirst_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

{% if request.current_page.get_children.0.get_absolute_url %}

2) In contrast to that, any issues in a view will immediately raise exceptions and be obvious to debug

first_child_url = request.current_page.get_children[0].get_absolute_url

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....


If you're the only developer, it's mostly a matter of taste. However, if the one coding the views is not the one writing the templates, it's much easier to cooperate with well-defined "contracts" between view and template.

I tend to think of the view's parameters to a template the same way I think about API interfaces. My website logic can change, but as long as I respect the data structure passed to the template, I don't need to rewrite anything -- and when working in a group, this is of vital importance.

0

精彩评论

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