日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

jinja2的转义详解

發布時間:2023/12/31 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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的转义详解的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。