django哲学:何时包含模板,何时让代码生成html



在使用Django模板时,我应该有一些类似"子例程"的模板吗?或者在这种情况下,我应该从代码中生成HTML吗?

例如,我有一个包含多个名称列表的模板,我想将每个名称列表转换为select。我是否应该有一个模板,将name_list变量渲染为select,并执行以下操作:

#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 %}

或者我的代码中应该有一个函数name_list_to_select_html,它做同样的工作,并这样做:

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

或者这两者都错了,而我的哲学完全错了?

附加问题:就速度而言,不断包含模板是否很慢?这是代码内html生成的加分项吗?

通常,HTML只能在模板系统或直接相关的代码中生成。这使数据视图与业务和功能逻辑完全分离。我觉得这是一个适当的关注分离。使用您的第一个解决方案。

至于性能,Django可能需要大约相同的时间来运行这两个代码。但是,如果您知道不需要在每个请求中重新生成这些代码段,那么它具有内置的视图和模板片段缓存。

最新更新