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.
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>
When you run main.py and access http: // localhost: 5000 /
I will come out.
Recommended Posts