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

如何跨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 php 将rtmp协议转hls协议,无法播放
  • ¥15 miniconda安装不了
  • ¥20 python代码编写
  • ¥20 使用MPI广播数据遇到阻塞
  • ¥15 TinyMCE如何去掉自动弹出的“链接…”工具?
  • ¥15 微信支付转账凭证,如何解决
  • ¥15 在win10下使用指纹登录时,界面上的文字最后一个字产生换行现象
  • ¥20 使用AT89C51微控制器和MAX7219驱动器来实现0到99秒的秒表计数,有开始和暂停以及复位功能,下面有仿真图,请根据仿真图来设计c语言程序
  • ¥15 51单片机 双路ad同步采样
  • ¥15 使用xdocreport 生成word