FAQ

On Mon, Sep 3, 2012 at 9:58 AM, Yaşar Arabacı wrote:
Hi,

I have finished http://golang.org/doc/articles/wiki/ , and I am trying
add some things on it. I think I could put all templates inside tmpl/
and read whatever is there. I did this (unrelated parts omitted);

However, when I visit editing page, I get `html/template:
"tmpl/edit.html" is undefined`. What am I doing wrong here? Additional
comment is also welcome about how I use the language, as I am new and
trying to get used to it.
ParseFiles names templates using the base name of the file, so you
should be executing "edit.html" not "tmpl/edit.html". Also,
filepath.Walk can make your code much simpler:

walk := func(path string, info os.FileInfo, err error) error {
if err == nil && !info.IsDir() && filepath.Ext(path) == ".html" {
// Load template
}
return err
}
err := filepath.Walk(root, walk)

- Max

Search Discussions

  • Yaşar Arabacı at Sep 3, 2012 at 2:31 pm
    Hi,

    I have finished http://golang.org/doc/articles/wiki/ , and I am trying
    add some things on it. I think I could put all templates inside tmpl/
    and read whatever is there. I did this (unrelated parts omitted);

    const TMPLDIR = "tmpl/"
    var templates *template.Template

    func readTemplates(dir string) (templates *template.Template, err error){

    filenames := make([]string,0,16)

    file, err := os.Open(dir)
    if err != nil {
    return nil, err
    }

    fi, err := file.Readdir(0)
    if err != nil {
    return nil, err
    }

    for _, k := range fi {
    if k.IsDir() {
    continue
    }
    if strings.HasSuffix(k.Name(), ".html") {
    filenames = append(filenames, dir + k.Name())
    }
    }
    templates = template.Must(template.ParseFiles(filenames...))
    return
    }

    func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
    err := templates.ExecuteTemplate(w, TMPLDIR + tmpl+".html", p)
    if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
    }
    }

    func main() {
    var err error
    templates, err = readTemplates(TMPLDIR)
    if err != nil {
    return
    }
    // rest was here
    }

    However, when I visit editing page, I get `html/template:
    "tmpl/edit.html" is undefined`. What am I doing wrong here? Additional
    comment is also welcome about how I use the language, as I am new and
    trying to get used to it.

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
groupgolang-nuts @
categoriesgo
postedSep 3, '12 at 2:14p
activeSep 3, '12 at 2:31p
posts2
users2
websitegolang.org

2 users in discussion

Yaşar Arabacı: 1 post Maxim Khitrov: 1 post

People

Translate

site design / logo © 2022 Grokbase