如何将结构体渲染为html模板?

时间:2016-09-23 07:45:03

标签: go

我将用数据渲染html,渲染时,我不知道如何在控制器上渲染其他文件的struct for render,

代码:

packages controller

type Index struct {
Title string
Body  string
}

func IndexController(w http.ResponseWriter , r *http.Request){

if r.Method == "POST"{

    data := &Index{
        Title: "Hello",
        Body:  "Welcome to the WebGo.",
    }

    ff := renders.Sample{Temppath:"templates/index.tmpl",Data:data}
    ff.Render(w)

我的渲染包:

package renders

import (
   "html/template"
   "log"
   "net/http"
 )

type Sample struct {
  Temppath string
  Data struct{}   ## i don't know how to use pass value of package controller to renders package ?
}

func (obj Sample) Render(w http.ResponseWriter) error {

 var indexTemplate = template.Must(template.ParseFiles(obj.Temppath))
 if err := indexTemplate.Execute(w, obj.Data); err != nil {
    log.Println(err)
    return err
 }
 return nil
}

html代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="/static/js/sample.js"></script>
    <title>{{.Title}}</title>
    <style>
        body {
            font-family: sans-serif;
        }
        h1 {
            background: #ddd;
        }
        #sidebar {
            float: right;
        }
    </style>
</head>
<body>
    <h1>{{.Title}}</h1>
    <div id="sidebar">
        {{block "sidebar" .}}

        <ul>

        </ul>
        {{end}}
    </div>

    {{block "content" .}}
    <div id="content">
        {{.Body}}
    </div>
    {{end}}
</body>

</html>

如何将type Index struct传递给渲染包使用indexTemplate.Execute(w, obj.Data)

1 个答案:

答案 0 :(得分:2)

将结构Data中的字段Sample声明为interface{}

type Sample struct {
    Temppath string
    Data     interface{}
}

然后,类型Sample也可以在其他控制器中用作将要传递给模板的任何数据的占位符。