登录
首页 >  Golang >  Go问答

在golang gin简单模板示例中,如何渲染不带引号的字符串?

来源:stackoverflow

时间:2024-04-14 20:57:33 268浏览 收藏

从现在开始,我们要努力学习啦!今天我给大家带来《在golang gin简单模板示例中,如何渲染不带引号的字符串?》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!

问题内容

使用 readme 中的示例 golang gin 代码:

func main() {

  router := gin.Default()

  router.LoadHTMLGlob("templates/*")
  router.GET("/", func(c *gin.Context) {
    c.HTML(http.StatusOK, "index.tmpl",
      gin.H{
        "foo": "bar",
      })
  }
}

// in template index.tmpl



// result in html

但是我怎样才能在没有引号的情况下得到它,我只需要 bar"bar"


解决方案


模板包实现了 html 上下文感知引擎来提供注入安全的 html。

换句话说,它知道自己在 script 标签内执行,因此它不会输出原始字符串,而是与 js 兼容的 json 编码字符串。

要修复此问题,与评论建议的不同,请将字符串设置为 template.js 值,并且安全措施不会尝试保护字符串。

参考 - https://golang.org/pkg/html/template/

包模板(html/template)实现数据驱动模板 生成可安全防止代码注入的 html 输出。

使用这种类型会带来安全风险:封装的内容 应来自可信来源,因为它将逐字包含在 模板输出。

package main

import (
    "html/template"
    "os"
)

func main() {

    c := ``
    d := map[string]interface{}{"foo": "bar", "oof": template.JS("rab")}
    template.Must(template.New("").Parse(c)).Execute(os.Stdout, d)
}

https://play.golang.org/p/6qLnc9ALCeC

以上就是《在golang gin简单模板示例中,如何渲染不带引号的字符串?》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>