猿问

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

我正在使用 gin 模板并呈现我使用的 HTML


c.Writer.Header().Set("username", "myname")

c.HTML(200, "myservices", gin.H{

    "title":    "Dashboard",

    "username": "myname" })

我想传递一个变量(用户名),以便我可以在附加到我的模板的 js 文件中访问它。我可以使用模板访问用户名变量{{.username}}。如何使其全局化,以便我也可以在所有 js 文件中访问它。我尝试在标题中设置它,但只有在加载 HTML 时才能访问它。在加载模板之前我将无法使用它。


SMILET
浏览 324回答 1
1回答

呼啦一阵风

您可以将 Javascript 代码插入到<head>您创建 Javascript 变量的 HTML 页面(例如,在该部分中),并使用传递给模板执行的参数初始化它们。看这个例子:func main() {&nbsp; &nbsp; t := template.Must(template.New("").Parse(templ))&nbsp; &nbsp; m := map[string]interface{}{&nbsp; &nbsp; &nbsp; &nbsp; "title":&nbsp; &nbsp; "Test page",&nbsp; &nbsp; &nbsp; &nbsp; "username": "bob",&nbsp; &nbsp; &nbsp; &nbsp; "counter":&nbsp; 12,&nbsp; &nbsp; }&nbsp; &nbsp; if err := t.Execute(os.Stdout, m); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }}const templ = `<html><head><script>&nbsp; &nbsp; var _title = {{.title}};&nbsp; &nbsp; var _username = {{.username}};&nbsp; &nbsp; var _counter = {{.counter}};</script></head><body></body></html>`这会生成一个 HTML 文档(在Go Playground上试试):<html><head><script>&nbsp; &nbsp; var _title = "Test page";&nbsp; &nbsp; var _username = "bob";&nbsp; &nbsp; var _counter =&nbsp; 12 ;</script></head><body></body></html>这意味着页面中的其他 Javascript 代码(内联或引用的,外部的)将看到变量_title,并将它们用作常规变量,并使用我们传递给的值初始化_username它们。_counterTemplate.Execute()请注意,该html/template包执行上下文转义。看到它{{.title}}在引号中插入了结果,因为它是 a string,这就是它应该用 Javascript 代码编写的方式,但是在插入 的结果时没有添加引号{{.counter}},因为它是 type 的值int。另请注意,您应该使用唯一的命名策略以避免与现有变量或可能在其他 Javascript 代码中使用的变量发生冲突。通常一个特殊的前缀(或后缀)会这样做。
随时随地看视频慕课网APP

相关分类

Go
我要回答