dougai6464 2016-08-26 07:13
浏览 337
已采纳

如何跨HTML go-gin的所有js文件访问变量

I am using gin templating and to render an HTML I use

c.Writer.Header().Set("username", "myname")
c.HTML(200, "myservices", gin.H{
    "title":    "Dashboard",
    "username": "myname" })

I want to pass a variable (username) so that I can access that in the js files attached to my template. I can access the username variable in template using {{.username}}. How can make it global so that I can also access it across all the js files as well. I tried setting it in header but I can access that only when the HTML is loaded. I won't be able to use it before the template is loaded.

  • 写回答

1条回答 默认 最新

  • doufei5315 2016-08-26 07:20
    关注

    You can insert a Javascript code into the HTML page (e.g. in the <head> section) where you create Javascript variables, and initialize them with the parameters passed to the template execution.

    See this example:

    func main() {
        t := template.Must(template.New("").Parse(templ))
        m := map[string]interface{}{
            "title":    "Test page",
            "username": "bob",
            "counter":  12,
        }
        if err := t.Execute(os.Stdout, m); err != nil {
            panic(err)
        }
    }
    
    const templ = `<html><head>
    <script>
        var _title = {{.title}};
        var _username = {{.username}};
        var _counter = {{.counter}};
    </script>
    </head><body>
    </body>
    </html>`
    

    This results in an HTML document (try it on the Go Playground):

    <html><head>
    <script>
        var _title = "Test page";
        var _username = "bob";
        var _counter =  12 ;
    </script>
    </head><body>
    </body>
    </html>
    

    What this means is that other Javascript code in the page (either inlined or referenced, external) will see the variables _title, _username, _counter and use them as regular variables, and they are initialized with values we passed to Template.Execute().

    Note that the html/template package performs contextual escaping. See that it inserted the result of {{.title}} in quotes because it is a string and that is how it should be written in Javascript code, but no quotes were added when inserting the result of {{.counter}}, because it is a value of type int.

    Also note that you should use a unique naming strategy to avoid collision with existing variables or variables that may be used in other Javascript code. Usually a special prefix (or postfix) does it.

    Also check out this related question: Referencing Go array in Javascript

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决