2017-08-04 68 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() 

運行該應用程序並注意瀏覽器中的標題更改。

相關問題