When using Django templates, should I have some templates that act like "subroutines", so to speak, or should I generate HTML from within my code in these cases?
For example, I have a template with several lists of names, each of which I want to turn into a select. Should I have a template that renders the name_list variable into a select, and do something like this:
#in the view:
return {'name_list_1': name_list_1,
'name_list_2': name_list_2,
'name_list_3': name_list_3}
#in the template:
{% with name_list_1 as name_list %}
{% include "sub_name_list_select.html" %}
{% endwith %}
{% with name_list_2 as name_list %}
{% include "sub_name_list_select.html" %}
{% endwith %}
{% with name_list_3 as name_list %}
{% include "sub_name_list_select.html" %}
{% endwith %}
Or should I have a function in my code, name_list_to_select_html, which does the same job, and do this:
return {'name_list_1_html': name_list_to_select_html(name_list_1),
'name_list_2_html': name_list_to_select_html(name_list_2),
'name_list_3_html': name_list_to_select_html(name_list_3)}
#in the template:
{{ name_list_1_html|safe }}
{{ name_list_2_html|safe }}
{{ name_list_3_html|safe }}
Or are both of these wrong and I am getting the philosophy totally wrong?
Additional question: in terms of speed, is it slow to constantly include templates? Is that a bonus point for the in-code html generation?
-
stackoverflow.com/faq#dontask. This might be more appropriate some place like codereview.stackexchange.comChris Pratt– Chris Pratt2012年07月19日 20:26:41 +00:00Commented Jul 19, 2012 at 20:26
-
which particular criteria does this question fall under? it seems pretty straightforward to me: how do django developers accomplish this task?Claudiu– Claudiu2012年07月19日 21:20:14 +00:00Commented Jul 19, 2012 at 21:20
-
It's a subjective question. The bulleted list merely provides examples of common subjective questions, but if you're asking what people recommend, your question is subjective and not appropriate for StackOverflow. Like I said, the Code Review site would be okay because the entire nature of that site is to gain subjective opinions.Chris Pratt– Chris Pratt2012年07月19日 21:29:59 +00:00Commented Jul 19, 2012 at 21:29
-
@ChrisPratt: ah ok, i think you're right. voting to close the question.Claudiu– Claudiu2012年07月20日 03:12:22 +00:00Commented Jul 20, 2012 at 3:12
1 Answer 1
Generally, HTML should only be generated in the templating system or directly related code. That keeps the view of the data completely separate from the business and functional logic. I feel that's a proper separation of concerns. Go with your first solution.
As for performance, Django should probably take around the same amount of time running either code. But it has built-in view and template fragment caching if you know those segments of code don't need to be regenerated on every request.
3 Comments
views.py enough separation?Explore related questions
See similar questions with these tags.