如何在Django模板中从视图中打印HTML内容?

huangapple go评论98阅读模式
英文:

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'})

huangapple
  • 本文由 发表于 2023年2月27日 15:04:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75577553.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定