我確實承認這個問題是在一年前問過的,但問題仍然存在。 Flask-Themes目前無法使用。因爲這個,我必須找到一種方法來自己做。
其實這是一個微不足道的過程。
乾淨的結構對於以後的維護必不可少(即使它是一個作者的項目)。
所以,努力適應奧茲坎的結構,有多個模板配置,我們可以有這樣的結構:
/python
_ _ _ _app.py
_ _ _ _config.py
______/templates
________________/default
_ _ _ _ _ _ _ _ _ _ _ _index.html
________________/custom
_ _ _ _ _ _ _ _ _ _ _ _index.html
我不知道是什麼代碼/在他的應用程序文件,但我想,在app.py有這樣的事情:
from flask import Flask, render_template
import config
app = Flask(__name__, template_folder='/templates/' + config.Config.ACTIVE_THEME)
@app.route('/')
def main():
return render_template('index.html')
if '__name__' == '__main__':
app.run()
的config.py這樣的:
class Config(object):
ACTIVE_THEME='default'
在模板的默認主題的index.html文件夾可能是這樣的:
<head>
# We have the ability to include the css from the current path instead of having a separate static folder
<style type='text/css'> {% include 'style.css' %} </style>
</head>
<body>
<h1> This is the "default" theme </h1>
</body>
而且定製主題的index.html像這樣:
<head>
<style type='text/css'> {% include 'style.css' %} </style>
</head>
<body>
<h1> This is the "custom" theme </h1>
</body>
現在,訪問127.0.0.1:5000
將顯示「這是」默認「主題」,因爲實際上已加載默認主題。
要改變這一點,你不得不修改配置文件以下列方式:
class Config(object):
# Set ACTIVE_THEME from default to custom
ACTIVE_THEME='custom'
保存更改,重新加載頁面,你應該看到「這是‘定製’主題」。
這是一個非常基本的「黑客」,但我建議使用藍圖,如果你認真對待你的應用程序,除此之外不得不維護2個配置文件而不是一個配置文件。
爲了避免這些問題,我使用藍圖和一個良好的應用程序結構。
比如我定義了應用程序初始化等等的,而不是像這樣後配置:
import config
app = Flask(__name__, template_folder=/templates/' + config.Config.ACTIVE_THEME)
它是這樣的:
app = Flask(__name__)
app.config.from_object('config.Config')
而且在所有的一個單獨的文件視圖,在頂部的下面的行:
# doing an "import app" would raise an error because of it being a circular import
import config
active_theme = config.Config.ACTIVE_THEME
# Watch out for the second argument as it seems to add a prefix to successive defined arguments. In fact you could swap the "themes" part to it and remove it from the third argument, but I prefer to leave it like this to avoid future headaches.
posts = Blueprint('posts', '', template_folder='templates/' + active_theme + '/post')
它也可以通過其它方式如使用擴展數據庫配置等。
希望這可以幫助別人。
你見過[Flask-Themes](https://pypi.python.org/pypi/Flask-Themes)嗎?如果是這樣,它缺少什麼(以便我們知道你的特定問題是什麼)? – 2013-02-26 02:04:53
我的問題是無法使它工作,不是嗎? – saidozcan 2013-02-26 07:34:09
@SeanVieira看到我的答案,它不工作/有一個錯誤atm。 – 2014-04-28 13:42:20