Template Inheritance porblem

xuanbao · 2018-06-14 12:30:10 · 754 次点击    
这是一个分享于 2018-06-14 12:30:10 的资源,其中的信息可能已经有所发展或是发生改变。

Hello, I am passing data from controller to template "index.html" to render them.

index.html file includes from sidebar.html, so index.html file is made up of sidebar.html too

The problem is that, if I try to access data inside sidebar.html, it is empty.

What is the solution?


评论:

tgaz:

https://golang.org/pkg/text/template/:

{{template "name"}}
    The template with the specified name is executed with nil data.
{{template "name" pipeline}}
    The template with the specified name is executed with dot set
    to the value of the pipeline.

You should be using the second form, and likely pass dot as the pipeline.

ComfortablyNull:

Are you using the template package?

If so you probably have to pass the data to the sidebar template with '.' :

Quick and dirty example:

package main
import (
    "html/template"
    "os"
)
// Notice the '.' being passed after the template name. 
// This passes all the curently scoped data to the template
const index = `{{ .hello }} {{template "sidebar" .}}`
const sidebar = `{{ .bye }}`
func main() {
    data := map[string]string{"hello": "hello", "bye": "goodbye!"}
    template.ParseFiles()
    sideBarTemplate, err := template.New("sidebar").Parse(sidebar)
    if err != nil {
        panic(err)
    }
    t, err := sideBarTemplate.New("index").Parse(index)
    if err != nil {
        panic(err)
    }
    t.Execute(os.Stdout, data)
}

This should output:

hello goodbye!

CrappyFap69:

It works like a charm!

LaughingCabbage_:

<html> <body>{{ .class.member }}</body> </html>


入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

754 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传