jinja2的转义详解
網上關于jinja2轉義的博客很多,
但是不夠清晰,決定還是自己寫一篇
轉義的官方定義如下[1]:
HTML EscapingWhen generating HTML from templates, there’s always a risk that a variable will include characters that affect the resulting HTML. There are two approaches: manually escaping each variable or automatically escaping everything by default.Jinja supports both, but what is used depends on the application configuration. The default configuaration is no automatic escaping for various reasons:escaping everything except of safe values will also mean that Jinja is escaping variables known to not include HTML such as numbers which is a huge performance hit. The information about the safety of a variable is very fragile. It could happen that by coercing safe and unsafe values the return value is double escaped HTML.看著還是有點含糊對吧
#--------------------------------------------------實驗對比----------------------------------------------------------------------------------------
python hello.py(完整工程代碼見文末)
瀏覽器打開:
http://127.0.0.1:5000/hello
轉義生效效果:
轉義失效效果:
?
總結:
| html文件中 轉義設置代碼 | 轉義生效嗎? | 具體效果 |
| {% autoescape False %} | 生效 | |
| {% autoescape True %} | 不生效 | |
| {% autoescape None %} | 生效 |
?
注意:
每次修改html,都要重啟,才能讓html修改結果生效,
這一點和python后端不同,后端是你直接修改代碼后,無需重啟api就能讓修改生效的
#----------------------------------------------附錄------------------------------------------------------------------------------------
工程結構:
├── hello.py
└── templates
? ? └── hello.html
hello.py文件:
from flask import Flask from flask import render_template app = Flask(__name__)@app.route('/hello') @app.route('/hello/<name>') def hello(name=None):if name is None:name = '<em>World</em>'return render_template('hello.html', name=name)if __name__ == '__main__':app.run()hello.html文件(轉義生效狀態1):
{% autoescape None %}<h1>Hello {{ name }}!</h1> {% endautoescape %}hello.html文件(轉義生效狀態2):
{% autoescape False?%}<h1>Hello {{ name }}!</h1> {% endautoescape %}hello.html文件(轉義失效狀態):
{% autoescape True %}<h1>Hello {{ name }}!</h1> {% endautoescape %}
Reference:
[1]Jinja2與Flask的HTML自動轉義 vimtest
?
總結
以上是生活随笔為你收集整理的jinja2的转义详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 大众点评app怎么样
- 下一篇: jinja2语法中{%raw%}和{{}