英文:
How to print HTML content from a Django template in a view?
问题
以下是翻译好的部分:
def get_html():
html_content = some_function("index.html", {...}) # 接受模板名称和上下文
print(html_content)
这个代码段询问是否可以在Django中执行。
英文:
Let's say I have a template called index.html
with a bunch of block tags and variables and URLs. I can display it from my view using the render()
function like so:
def index(request):
return render(request, "index.html", {...})
I would like to print the actual content that is being generated here in a normal python function. Something like this:
def get_html():
html_content = some_function("index.html", {...}) # Takes in the template name and context
print(html_content)
Is this possible to do using Django?
答案1
得分: 2
你可以使用 render_to_string
函数。因为 render
内部使用此函数 来构建HTML内容,然后将其传递给 HTTPResponse
类以从视图构建适当的响应。
from django.template.loader import render_to_string
rendered = render_to_string('my_template.html', {'foo': 'bar'})
英文:
You can use render_to_string
function. Because render
internally uses this function to build the HTML content and it simply pass it down to HTTPResponse
class to build the appropriate response from the view.
from django.template.loader import render_to_string
rendered = render_to_string('my_template.html', {'foo': 'bar'})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论