一種可能性是創建一個自定義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()
運行該應用程序並注意瀏覽器中的標題更改。
這個問題很不清楚。通常情況下,您將所有信息傳遞給Flask代碼中的模板,因此您應該解釋爲什麼您無法做到這一點。 –
@DanielRoseman:[有時](https://github.com/lingthio/Flask-User-starter-app/blob/1c892d57dc1aff550d171c017031a45b2905d66b/app/templates/layout.html#L27)模板代碼可以(a)中需要被編輯(b)由所有其他模板使用。我希望能夠從代碼編輯該基本模板。 – DuckQueen