LoginSignup
3
2

More than 3 years have passed since last update.

Flaskのテンプレートエンジンの予約語を変更する

Last updated at Posted at 2020-01-10

Flaskのテンプレート内の予約文字列 {{ }} {% %} を変更する方法を説明します。

これで何が嬉しいかというと、例えばVue.jsを使おうとするとVue.jsも {{ }} を使うので、Flaskと競合してしまいますが、この方法により回避できます。

環境

  • Flask==1.0.2
  • Jinja2==2.10.1

コード

以下の2つのコードで {{ }} {% %} を [[ ]] [% %] に変更できます。

main.py

from flask import Flask

# Flaskのテンプレートエンジンであるjinja2のenvironmentを作成。
from jinja2 import Environment, PackageLoader, select_autoescape
jinja2_environment = Environment(
    loader=PackageLoader(__name__, 'templates'),
    autoescape=select_autoescape(['html', 'xml']),
    block_start_string    ='[%',   #元は {%
    block_end_string      ='%]',   #元は %}
    variable_start_string ='[[',   #元は {{
    variable_end_string   =']]'    #元は }}
)

app = Flask(__name__)

@app.route('/')
def root():
    # 作ったenvironmentを指定してテンプレートを取得
    template = jinja2_environment.get_template('index.html')
    # テンプレートをレンダリング
    return template.render(var1="hello")

if __name__ == '__main__':
    app.run()

templates/index.html

<html>
  <body>
    [% if 1 > 0 %]
      [[ var1 ]]
    [% endif %]
  </body>
</html>

結果

main.pyを実行して、 http://localhost:5000/ にアクセスすると

image.png

とでます。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2