【问题标题】:Django - get HTML output into a variableDjango - 将 HTML 输出转换为变量
【发布时间】:2011-06-04 10:16:39
【问题描述】:

而不是使用render_to_response,它将HTML输出发送回浏览器。

我想获取结果,生成 HTML(使用模板)并将 html 输出到我的 views.py 中的变量中。我该怎么做?

【问题讨论】:

  • 回答自己的问题并没有错——StackOverflow 实际上鼓励这样做。如果你这样做了,你会得到我三倍的信任(问题 5 分,答案 10 分,而不是问题只有 5 分)。

标签: python django django-templates django-views


【解决方案1】:

已解决!这样做的方法 -

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

感谢 ned 指向Django docs

【讨论】:

  • 太棒了!很有用
  • 你好,我们可以从 db 获取它而不是硬编码 html 文件名吗?
【解决方案2】:

改编自Django docs

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

【讨论】:

  • 我可以传递html而不是Template("My name is {{ my_name }}."),即Template("trial.html")吗?
  • 你检查过the docs吗?
  • 不赞成这个,因为它没有回答关于使用模板文件(不是文本)的问题,并且回答者将其留给读者阅读文档。 >
  • 你好 @NedBatchelder ,我们可以从 db 获取它而不是硬编码 html 文件名吗?
【解决方案3】:

还有更简单的方法(如果需要从render方法中提取html数据):

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

【讨论】:

猜你喜欢
  • 2019-02-25
  • 1970-01-01
  • 2012-02-07
  • 1970-01-01
  • 1970-01-01
  • 2020-02-05
  • 1970-01-01
  • 1970-01-01
  • 2016-09-03
相关资源
最近更新 更多