如何在创建应用程序时更新template_string?

时间:2017-08-04 18:59:33

标签: python templates flask

假设我们使用Flask-User显示基本登录\ logout \ edit用户页面\主页面内容。然而他们的base.html并不完美(例如静态应用程序名称嵌入到base.html中)。假设我们的应用程序只能有一个python脚本文件(依赖项 - 是的,额外的.html模板文件 - 否)。如何直接从python代码编辑Flask template_string(对于base.html)?

1 个答案:

答案 0 :(得分:1)

One possibility is to create a custom FileSystemLoader class and modify the appropriate template contents returned from its get_source method.

A simple example:

base.html This is the template we want to modify. Suppose we don't like the contents of the title tag.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title set in base template</title>
</head>
<body>

{% block content %}
{% endblock content %}

</body>
</html>

index.html This is our template that extends base.html.

{% extends 'base.html' %}

{% block content %}
    <h1>Home Page</h1>
{% endblock content %}

app.py Our simple Flask app.

import os
from flask import Flask, render_template
from jinja2 import FileSystemLoader


class CustomFileSystemLoader(FileSystemLoader):

    def __init__(self, searchpath, encoding='utf-8', followlinks=False):
        super(CustomFileSystemLoader, self).__init__(searchpath, encoding, followlinks)

    def get_source(self, environment, template):
        # call the base get_source
        contents, filename, uptodate = super(CustomFileSystemLoader, self).get_source(environment, template)

        if template == 'base.html':
            print contents
            # Modify contents here - it's a unicode string
            contents = contents.replace(u'Title set in base template', u'My new title')

            print contents

        return contents, filename, uptodate


app = Flask(__name__)

app.jinja_loader = CustomFileSystemLoader(os.path.join(app.root_path, app.template_folder))


@app.route('/')
def home():
    return render_template('index.html')


if __name__ == '__main__':
    app.run()

Run the app and notice the title change in the browser.