Claudiu
Claudiu

Reputation: 229361

django philosophy: when to include templates and when to have code generate html?

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?

Upvotes: 1

Views: 235

Answers (1)

Matt S
Matt S

Reputation: 15374

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.

Upvotes: 3

Related Questions