简体   繁体   English

Django - 将HTML输出转换为变量

[英]Django - get HTML output into a variable

instead of using render_to_response which will send the HTML output back to browser. 而不是使用render_to_response ,它将HTML输出发送回浏览器。

I would like to take the results, generate HTML (using templates) & output the html into a variable in my views.py . 我想取结果,生成HTML(使用模板)并将html输出到我的views.py的变量中。 How can I do this? 我怎样才能做到这一点?

SOLVED! 解决了! the way to do this - 这样做的方式 -

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

thanks to ned for pointing to the Django docs 感谢ned指向Django文档

Adapted from the Django docs : 改编自Django文档

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

There is even a simpler way (if you need to extract html data from render method): 甚至有一种更简单的方法(如果你需要从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