在Flas中插入HTML的正确方法

2024-05-16 16:06:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道如何在访问URL时使用render_模板从Python发送纯文本:

@app.route(/success.html")
...
return render_template("index.html", text="This text goes inside the HTML")

模板应该是这样的:

<div class="output">
  {{text|safe}}
 </div>

但是,当我需要插入几行HTML时,我不知道该怎么做。例如,表单:

<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脚本中将其作为字符串加载并发送到模板中,它可能会工作,但这听起来不太正确。

有人知道如何正确地将HTML插入Flask网页吗?一个虚拟的例子也很好。


Tags: textnamedivform模板urlinputvalue
3条回答

Flask使用Jinja2模板引擎(两者都有相同的开发人员),当使用render_template("filename", "content")时,将在templates文件夹中查找具有该文件名的模板。 如果应用程序是一个模块,则此文件夹应位于该模块旁边,如下所示:

/application.py
/templates
    /hello.html

如果是包裹,它需要放在你的包裹里,比如:

/application
    /__init__.py
    /templates
        /hello.html

I want to figure out how to insert a HTML snippet into an existing template...

您可以使用Jinja2^{}指令。

{% include 'your_form.html' %}

... and where to store that snippet.

因此,您可以将表单放入自己的模板中,名为your_form.html,其中包含以下内容:

<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.

引用docs

If you access variables inside tags don’t put the braces around them.

所以很简单:

{% include html_file %}

如果您使用的是旧版本,这里有一个简单的方法

{% include '%s' % html_file %}

为了说明它的灵活性,这里有一些例子给你灵感

{% 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,因为它是动态的,如果该值来自客户端,则可能会公开您自己的文件

模板继承对于html重用也很有用。您可以添加基本模板并将自定义html代码/块添加到子html代码。

Base Template:

<!doctype html>
<html>
  <head>
    {% block head %}
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    <title>{% block title %}{% endblock %} - My Webpage</title>
    {% endblock %}
  </head>
  <body>
    <div id="content">{% block content %}{% endblock %}</div>
    <div id="footer">
      {% block footer %}
      &copy; Copyright 2010 by <a href="http://domain.invalid/">you</a>.
      {% endblock %}
    </div>
  </body>
</html>

Child Template:

{% extends "layout.html" %}
{% block title %}Index{% endblock %}
{% block head %}
  {{ super() }}
  <style type="text/css">
    .important { color: #336699; }
  </style>
{% endblock %}
{% block content %}
  <h1>Index</h1>
  <p class="important">
    Welcome on my awesome homepage.
{% endblock %}

来源:http://flask.pocoo.org/docs/0.12/patterns/templateinheritance/

相关问题 更多 >