I'm trying to build a basic MVC with Go and I try to copy a familier folder
structure that I used under Express/Koa in Node.js.
I have the following folder structure under the `*./views*` folder:
*│ index.html│├───layouts│ main.html│└───partials
footer.html header.html*
I parsing the template files with the following code in `
*./middlewares/templates.go*` file:
package middlewares
import (
"html/template"
"os"
"path/filepath"
"strings"
)
// GetAllFilePathsInDirectory : recursively get all file paths in dir +
sub-dirs
func GetAllFilePathsInDirectory(dirpath string) ([]string, error) {
var paths []string
err := filepath.Walk(dirpath, func(path string, info os.FileInfo, err
error) error {
if err != nil {
return err
}
if strings.HasSuffix(path, ".html") && !info.IsDir() {
paths = append(paths, path)
}
return nil
})
if err != nil {
return nil, err
}
return paths, nil
}
// ParseDirectory : recursively parse all files in dir + sub-dirs
func ParseDirectory(dirpath string, file string) (*template.Template, error)
{
paths, err := GetAllFilePathsInDirectory(dirpath)
if err != nil {
return nil, err
}
//fmt.Println(paths) // logging
t := template.New(file)
return t.ParseFiles(paths...)
}
I rendering my templates in the `*./controllers/index.go*` file with this:
package controllers
import (
"log"
"net/http"
mw "github.com/djviolin/lanti-mvc/src/middlewares"
)
// Index : is the index handler
func Index(w http.ResponseWriter, r *http.Request) {
render, err := mw.ParseDirectory("./views", "index")
if err != nil {
log.Fatal("Parse: ", err)
return
}
render.Execute(w, map[string]string{"Title": "My title", "Body": "This
is the body"})
}
My template files:
`*./views/index.html*`:
{{define "index"}}
<h1>Nested here</h1>
<ul>
<li>Nested usage</li>
<li>Call template</li>
</ul>
<p>main content: {{ . }}</p>
{{end}}
`*./views/layouts/main.html*`:
{{template "header" .}}
{{template "content" .}}
{{template "footer" .}}
`*./views/partials/header.html*`:
{{define "header"}}
<html>
<head>
<title>Something here</title>
</head>
<body>
{{end}}
`*./views/partials/footer.html*`:
{{define "footer"}}
</body>
</html>
{{end}}
How can I achieve that I define `*index*` in the controller file and `
*main.html*` rendering that file accordingly (so `*{{template "content" .}}*
` should be universal block, where rendering that template file from the `
*./views*` parent directory that I specified in the controller)?
Thank You for your help!
István
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.