我有一個 Django 驅動的網站,其中有幾個動態更新的應用程式,但不是太頻繁,比如“關于”、“我們的服務”等。它們有兩級頁面結構,我想在頂部反映彈出選單(見圖)。
我可以將其設定為每次從 base.html 模板呼叫的自定義 simple_tag。它會在用戶每次打開或重新加載頁面時生成一個選單,但認為這是非常昂貴的,因為應用程式結構很少更改(例如,一年一次)。

相反,我想在每次更新應用程式結構時生成選單的 HTML 代碼。它將存盤為靜態 HTML 檔案,因此我的 base.html 將包含選單作為準備好的代碼。
是否有關于如何從視圖(CreateView、UpdateView、DeleteView)生成 HTML 檔案的方法?
uj5u.com熱心網友回復:
您可以使用render_to_stringdjango 中從模板生成 html 結果的函式:
from django.template import loader
content = loader.render_to_string(template_name, context)
content 包含渲染的html結果。render_to_string如果需要,您可以在函式中添加請求物件。
你可以在這里找到關于函式的檔案:https ://docs.djangoproject.com/en/4.1/topics/templates/#django.template.loader.render_to_string
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/529538.html
標籤:django文件模板看法
