将HTML插入Flask的正确方法 [英] Proper way to insert HTML into Flask
问题描述
我知道在访问URL时如何使用render_template从Python发送一些纯文本:
I know how to send some plain text from Python with render_template when a URL is visited:
@app.route(/success.html")
...
return render_template("index.html", text="This text goes inside the HTML")
模板将具有以下内容:
<div class="output">
{{text|safe}}
</div>
但是,当我需要插入几行HTML时,我不确定该怎么办.例如,一种形式:
However, I am not sure what to do when I need to insert a few lines of HTML. For example, a form:
<form action="">
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car
</form>
如果我将其作为字符串加载到Python脚本中并将其发送到模板,则可能会起作用,但这听起来不太正确.
It will probably work if I load this as a string in the Python script and send it to the template, but that doesn't sound quite right.
任何人都知道如何正确地将HTML插入Flask网页吗?一个虚拟的例子也很好.
Anyone knows how to properly insert HTML into a Flask webpage? A dummy example would also be great.
推荐答案
我想弄清楚如何将HTML代码段插入到现有模板中...
I want to figure out how to insert a HTML snippet into an existing template...
您可以使用Jinja2 > {%include%}
指令.
You can use the Jinja2 {% include %}
directive.
{% include 'your_form.html' %}
...以及该代码段的存储位置.
... and where to store that snippet.
因此,您将表单放入其自己的模板中,该模板名为 your_form.html
,其内容为:
So you'd put your form in a template of its own, called your_form.html
with the content:
<form action="">
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car
</form>
然后在您的 index.html
中将其包含
<div class="output">
{% include 'your_form.html' %}
</div>
Jinja2中的动态变量
我想动态渲染它.
I want to render it dynamically.
引用文档
如果您访问标记内的变量,请不要在其周围加上花括号.
If you access variables inside tags don’t put the braces around them.
那么简单:
{% include html_file %}
如果您使用的是旧版本,这是一种简单的方法
{% include '%s' % html_file %}
只是为了说明它的灵活性,这里有一些例子可以给您启发
Just to illustrate the flexibility of it, here's some examples to give you inspiration
{% include '%s.html' % name_without_extension %}
{% include 'templates/%s/forms/%s' % (company, template) %}
您还可以像这样设置Jinja变量(这是更详细的IMO)
{% set template_path = html_file %}
{% include template_path %}
安全提示:请确保您完全知道作为变量 html_file
传递的内容,因为它是动态的,如果该值来自客户端,则您可能会暴露您自己的文件
Security tip: Make sure you know exactly what is passed on as the variable html_file
, since it's dynamic, if that value comes from the client, you may be exposing your own files
这篇关于将HTML插入Flask的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!