2017-08-04 115 views
0

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

+0

这个问题很不清楚。通常情况下,您将所有信息传递给Flask代码中的模板,因此您应该解释为什么您无法做到这一点。 –

+0

@DanielRoseman:[有时](https://github.com/lingthio/Flask-User-starter-app/blob/1c892d57dc1aff550d171c017031a45b2905d66b/app/templates/layout.html#L27)模板代码可以(a)中需要被编辑(b)由所有其他模板使用。我希望能够从代码编辑该基本模板。 – DuckQueen

回答

1

一种可能性是创建一个自定义FileSystemLoader类,并修改其get_source方法返回相应的模板内容。

一个简单的例子:

base.html文件这就是我们要修改的模板。假设我们不喜欢title标签的内容。

<!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这是我们的模板扩展base.html

{% extends 'base.html' %} 

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

app.py我们简单的瓶的应用程序。

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() 

运行该应用程序并注意浏览器中的标题更改。

相关问题