我将用数据渲染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)
答案 0 :(得分:2)
将结构Data
中的字段Sample
声明为interface{}
:
type Sample struct {
Temppath string
Data interface{}
}
然后,类型Sample
也可以在其他控制器中用作将要传递给模板的任何数据的占位符。