gpt4 book ai didi

python - Django哲学: when to include templates and when to have code generate html?

转载 作者:行者123 更新时间:2023-11-30 23:42:12 26 4
gpt4 key购买 nike

当使用 Django 模板时,我是否应该有一些像“子例程”一样的模板,或者在这些情况下我应该从我的代码中生成 HTML?

例如,我有一个包含多个名称列表的模板,我想将每个名称都变成select。我是否应该有一个将 name_list 变量呈现到选择中的模板,并执行如下操作:

#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 只能在模板系统或直接相关的代码中生成。这使得数据 View 与业务和功能逻辑完全分离。我觉得这是一个合适的separation of concerns 。采用您的第一个解决方案。

就性能而言,Django 应该花费大约相同的时间来运行任一代码。但是,如果您知道不需要在每个请求上重新生成这些代码段,那么它具有内置 View 和模板片段缓存。

关于python - Django哲学: when to include templates and when to have code generate html?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11566711/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com