douwuli4512 2016-05-18 11:40
浏览 37
已采纳

Golang中的变量内部定义模板

I have 3 files here in Golang project, the idea is to render the index.html isnside the body of layout.html. It works.

But when I tried to pass a variable into the index.html, the console.log() did not rendered. When I move the console.log() to layout.html, I can see the content of the JSON from .tes.

Here are the project files.

layout.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{{.title}} | {{.project_name}}</title>
</head>
<body style="width:100%; height: 100%; overflow-x: visible">
<div id="wrapper" style="width:100%; height:100%; margin: 0 auto">
    {{template "contents"}}
</div>
</body>
</html>

index.html

{{define "contents"}}
<script>
    var x = {{.tes}};
    console.log(x)
</script>
{{end}}

router.go

func init() {
    // handler
    http.HandleFunc("/", RenderPage)
}

func RenderPage(w http.ResponseWriter, r *http.Request) {
    tes := map[string]interface{}{
        "item":"TEST3",
        "count":4567,
    }
    Data := map[string]interface{}{
        "title":"TEST1",
        "project_name":"TEST2",
        "tes":M.ToJSON(tes),
    }
    tmpl, err := template.ParseFiles("page/layout.html", "page/index.html")
    X.CheckError(err)
    err = tmpl.Execute(w, Data)
    X.CheckError(err)
}
  • 写回答

1条回答 默认 最新

  • dtz30833 2016-05-18 12:06
    关注

    In layout.HTML, you need to pass the context. You do that with a . dot.

        {{ template "contents" . }}
    

    Alternatively, you can pass the value of whatever var you want:

        {{ template "contents" .tes }}
    

    ...and within the contents template, the dot context will be just the value of .tes. That helps limit the scope of sub-templates, not having to dot-walk to get to a value.

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

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题