[英]django philosophy: when to include templates and when to have code generate html?
當使用Django模板時,我是否應該有一些類似“子程序”的模板,或者我應該在這些情況下從我的代碼中生成HTML?
例如,我有一個包含多個名稱列表的模板,每個名稱都要轉換成一個select
。 我是否應該有一個將name_list
變量呈現為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只應在模板系統或直接相關代碼中生成。 這使數據視圖與業務和功能邏輯完全分離。 我覺得這是一個適當的關注點分離 。 繼續你的第一個解決方案。
至於性能,Django應該花費大約相同的時間運行任一代碼。 但是,如果您知道不需要在每個請求上重新生成這些代碼段,它就具有內置視圖和模板片段緩存。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.