首頁  >  文章  >  後端開發  >  在模板中轉義“/”

在模板中轉義“/”

WBOY
WBOY轉載
2024-02-06 09:45:081037瀏覽

在模板中轉義“/”

問題內容

我想傳遞一個像「avatars/avatar.png」這樣的字串,但是當我將它傳遞給模板時,我得到了字符轉義。 所以我寫了一個傳遞給模板的函數:

var tpl *template.Template

func init() {
    tpl = template.Must(template.ParseGlob("1Forum/static/html/*.html"))
    tpl = tpl.Funcs(template.FuncMap{
        "unescape": func(s string) string {
            unescaped, err := url.PathUnescape(s)
            if err != nil {
                return s
            }
            return unescaped
        },
    })
}

{{unescape .User.Avatar}}

但我仍然收到“未定義函數“unes​​cape””。沒有定義 unescape 嗎?

“net/url”已導入。


正確答案


unescape 沒有定義嗎?

技術上來說不是。您確實定義了它,但您這樣做為時已晚。函數是否定義是在解析期間檢查的,而不是執行期間檢查的。您有 parseglob ,然後您執行 tpl.func(...) 。這是不正常的。

而是這樣做:

func init() {
    tpl = template.Must(template.New("t").Funcs(template.FuncMap{
        "unescape": func(s string) string {
            unescaped, err := url.PathUnescape(s)
            if err != nil {
                return s
            }
            return unescaped
        },
    }).ParseGlob("1Forum/static/html/*.html"))
}

請注意,轉義是一項安全功能,其發生取決於context 您正在使用其中的數據,並且unescape 可能不會幫助您「欺騙」您的方式,因為轉義將會完成在unescape輸出上,而不是其輸入上。

換句話說,當您執行 {{unescape .}} 時,解析器可能會根據上下文將其轉換為{{unescape . | urlescaper}}urlescaper 是一個內部轉義函數)。為了避免這種情況,當您想要在模板中逐字使用已知的安全字串時,您應該使用輸入字串而不是unescape

請參閱遊樂場範例

有關上下文、轉義、鍵入字串等的更多信息,請閱讀軟體包的文檔,一切都解釋得很清楚。

以上是在模板中轉義“/”的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除