【问题标题】:html/template: "layout" is undefinedhtml/模板:“布局”未定义
【发布时间】:2014-12-14 10:12:54
【问题描述】:

我尝试使用带有布局模板的 martini 框架:

package main

import (
    "github.com/go-martini/martini"
    "github.com/martini-contrib/render"
)

func main() {
    m := martini.Classic()

    m.Use(render.Renderer(render.Options{Directory: "./templates",
        Layout:     "layout",
        Extensions: []string{".tmpl"},
    }))

    m.Get("/", func(r render.Render) {
        r.HTML(200, "mainPage", map[string]interface{}{"Title": "some title", "H1": "some h1"})
    })

    m.Run()
}

在与此 main.go 文件相同的文件夹中,我得到文件夹 templateslayout.tmpl 文件:

<html xmlns="http://www.w3.org/1999/xhtml"></html>
<head></head>
<body>  
    <div id='left'>
        {{template "left" .}}
    </div>
    <div id='right'>
        {{template "right" .}}
    </div>
</body>

mainPage.tmpl 文件:

{{define "left"}}
  left content
{{end}}

{{define "right"}}
    right content
{{end}}

当我在浏览器中打开 http://localhost:3000/ 时,我看到错误: html/template: "layout" is undefined

【问题讨论】:

  • 没有使用过martini,但是由于您在启动应用程序时不在正确的目录中而导致模板在运行时失败是一个常见问题,您是否尝试过从主文件夹运行(模板的父级)?

标签: go martini


【解决方案1】:

我的问题是我从随机目录运行go 文件。为了解决这个问题,我将目录 (cd) 更改为 templates 文件夹的父级。

【讨论】:

    【解决方案2】:
    <html xmlns="http://www.w3.org/1999/xhtml"></html>
       <head></head>
       <body>  
        <div id='left'>
            {{template "left" .}}
        </div>
        <div id='right'>
            {{template "right" .}}
        </div>
    </body>
    

    &lt;/body&gt; 后面加上正确的html 关闭标签

    就是这样:

    <html xmlns="http://www.w3.org/1999/xhtml">
       <head></head>
       <body>  
        <div id='left'>
            {{template "left" .}}
        </div>
        <div id='right'>
            {{template "right" .}}
        </div>
    </body>
    </html>
    

    【讨论】:

    • 那个错字并没有影响我的错误“layout” is undefined
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-16
    • 1970-01-01
    • 2016-05-31
    • 1970-01-01
    • 2021-01-24
    • 1970-01-01
    相关资源
    最近更新 更多