簡體   English   中英

Django - 將HTML輸出轉換為變量

[英]Django - get HTML output into a variable

而不是使用render_to_response ,它將HTML輸出發送回瀏覽器。

我想取結果,生成HTML(使用模板)並將html輸出到我的views.py的變量中。 我怎樣才能做到這一點?

解決了! 這樣做的方式 -

from django.template.loader import render_to_string
rendered = render_to_string('my_template.html', { 'foo': 'bar' })

感謝ned指向Django文檔

改編自Django文檔

from django.template import Context, Template
t = Template("My name is {{ my_name }}.")
c = Context({"my_name": "Adrian"})
output = t.render(c)

甚至有一種更簡單的方法(如果你需要從render方法中提取html數據):

R = render('template.html', context)
data = str(R.content)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM