multitemplate

package
v0.0.0-...-c239fd8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 27, 2020 License: MIT Imports: 2 Imported by: 0

README

EOL-warning

This package has been abandoned on 2016-12-13. Please use gin-contrib/multitemplate instead.

This is a custom HTML render to support multi templates, ie. more than one *template.Template.

#Simple example

package main

import (
    "html/template"

    "github.com/gin-gonic/gin"
    "github.com/gin-gonic/contrib/renders/multitemplate"
)

func main() {
    router := gin.Default()
    router.HTMLRender = createMyRender()
    router.GET("/", func(c *gin.Context) {
        c.HTML(200, "index", data)
    })
    router.Run(":8080")
}

func createMyRender() multitemplate.Render {
    r := multitemplate.New()
    r.AddFromFiles("index", "base.html", "base.html")
    r.AddFromFiles("article", "base.html", "article.html")
    r.AddFromFiles("login", "base.html", "login.html")
    r.AddFromFiles("dashboard", "base.html", "dashboard.html")

    return r
}

##Advanced example

https://elithrar.github.io/article/approximating-html-template-inheritance/

package main

import (
	"html/template"
	"path/filepath"

	"github.com/gin-gonic/contrib/renders/multitemplate"
	"github.com/gin-gonic/gin"
)

func main() {
	router := gin.Default()
	router.HTMLRender = loadTemplates("./templates")
	router.GET("/", func(c *gin.Context) {
		c.HTML(200, "index.tmpl", gin.H{
			"title": "Welcome!",
		})
	})
	router.Run(":8080")
}

func loadTemplates(templatesDir string) multitemplate.Render {
	r := multitemplate.New()

	layouts, err := filepath.Glob(templatesDir + "layouts/*.tmpl")
	if err != nil {
		panic(err.Error())
	}

	includes, err := filepath.Glob(templatesDir + "includes/*.tmpl")
	if err != nil {
		panic(err.Error())
	}

	// Generate our templates map from our layouts/ and includes/ directories
	for _, layout := range layouts {
		files := append(includes, layout)
		r.Add(filepath.Base(layout), template.Must(template.ParseFiles(files...)))
	}
	return r
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Render

type Render map[string]*template.Template

func New

func New() Render

func (Render) Add

func (r Render) Add(name string, tmpl *template.Template)

func (Render) AddFromFiles

func (r Render) AddFromFiles(name string, files ...string) *template.Template

func (Render) AddFromGlob

func (r Render) AddFromGlob(name, glob string) *template.Template

func (*Render) AddFromString

func (r *Render) AddFromString(name, templateString string) *template.Template

func (Render) Instance

func (r Render) Instance(name string, data interface{}) render.Render

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL