この質問が 1 年前に出されたことは認めますが、問題はまだ残っています。Flask-Themes はこれまでのところ機能しません。このため、自分でそれを行う方法を見つけなければなりませんでした。
実際、それは些細なプロセスです。
クリーンな構造は、後のメンテナンスのために必須です (たとえそれが 1 人の作者のプロジェクトであっても)。
したがって、Özcan の構造を適応させて、複数のテンプレート構成を持つようにしようとすると、次のような構造を持つことができます。
/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'
変更を保存し、ページをリロードすると、「これは「カスタム」テーマです」と表示されます。
これは非常に基本的な「ハック」ですが、アプリに真剣に取り組んでいる場合は、設計図を使用することをお勧めします。これ以外には、1 つではなく 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')
ユーザーセッション、データベース構成など、他の手段で拡張することもできます。
これが誰かに役立つことを願っています。