[PYTHON] Change the reserved words in Flask's template engine

Describes how to change the reserved string {{``}} `` {% ``%} in a Flask template.

What makes me happy is that if you try to use Vue.js, for example, Vue.js will also use {{``}} , which will conflict with Flask, but you can avoid it this way.

environment

code

You can change {{``}} `` {% %} to [[ ]] [% %] with the following two codes.

main.py

from flask import Flask

#Created an environment for jinja2, Flask's template engine.
from jinja2 import Environment, PackageLoader, select_autoescape
jinja2_environment = Environment(
    loader=PackageLoader(__name__, 'templates'),
    autoescape=select_autoescape(['html', 'xml']),
    block_start_string    ='[%',   #originally{%
    block_end_string      ='%]',   #originally%}
    variable_start_string ='[[',   #originally{{
    variable_end_string   =']]'    #originally}}
)

app = Flask(__name__)

@app.route('/')
def root():
    #Get the template by specifying the created environment
    template = jinja2_environment.get_template('index.html')
    #Render template
    return template.render(var1="hello")

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

templates/index.html

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

result

When you run main.py and access http: // localhost: 5000 /

image.png

I will come out.

Recommended Posts

Change the reserved words in Flask's template engine
Change the list in a for statement
Change the device (drive) label in vfat format.
Change the font size of the legend in df.plot
Learn the design pattern "Template Method" in Python
Loop variables at the same time in the template
Specify the view URL in your Django template
Register words in the GiNZA (SudachiPy) user dictionary
Python reserved words
Change the time zone with Docker in Oracle Database