go-nic/gin でwebアプリを構築しております。
templateに関して、共通部分と画面固有部分を分けようと、multitemplateを使用し、layout.tmplとindex.tmplに分けました。
使用する3ファイルを下に記載します。
- main.go
- templates/layout.tmpl
- templates/index.tmpl
go
1// main.go 2 3package main 4 5import ( 6 "html/template" 7 8 "github.com/gin-contrib/multitemplate" 9 "github.com/gin-gonic/gin" 10) 11 12func main() { 13 router := gin.Default() 14 router.LoadHTMLGlob("templates/**/*") 15 router.HTMLRender = createRender() 16 17 router.GET("/", func(c *gin.Context) { 18 c.HTML(200, "index", gin.H{ 19 "param1": "this is a param1.", 20 "param2": "this is a param2.", 21 }) 22 }) 23 router.Run() 24} 25 26 27func createRender() multitemplate.Renderer { 28 r := multitemplate.NewRenderer() 29 r.AddFromFiles("index", "templates/layout.tmpl", "templates/index.tmpl") 30 return r 31}
html
1<!-- templates/layout.tmpl --> 2{{ define "layout.tpl"}} 3<!DOCTYPE html> 4<html> 5 <head> 6 <title>TITLE</title> 7 </head> 8 <body> 9 <div class="container"> 10 {{ template "content" }} 11 {{ .param1 }} 12 </div> 13 </body> 14</html> 15{{ end }}
html
1<!-- templates/index.tmpl --> 2{{ define "content" }} 3<div class="container-inner"> 4 {{ .param2 }} 5</div> 6{{ end }}
上記app.goで param1
と param2
というパラメータを与えているのですが、実際に表示されるページでは param1
のみ表示され、
index.tmplに記述してある param2
が表示されません。
ネストしたtemplateでサーバからの値を表示する方法はございますでしょうか。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。