html/template: "layout" is undefined

4k views Asked by At

I try to use martini framework with layout template:

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()
}

In the same folder as this main.go file I got folder templates with layout.tmpl file:

<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>

and mainPage.tmpl file:

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

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

When I open http://localhost:3000/ in browser I see error: html/template: "layout" is undefined

2

There are 2 answers

0
Maxim Yefremov On BEST ANSWER

My problem was that I run go file from random directory. To solve it I changed directory (cd) to parent of templates folder.

1
bikbah On
<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>

Make correct html close tag after </body>

That`s it:

<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>