Goview is a lightweight, minimalist and idiomatic template library based on golang html/template for building Go web application.

Overview

goview

GoDoc Widget Travis Widget GoReportCard Widget

Goview is a lightweight, minimalist and idiomatic template library based on golang html/template for building Go web application.

Contents

Install

go get github.com/foolin/goview

Features

  • Lightweight - use golang html/template syntax.
  • Easy - easy use for your web application.
  • Fast - Support configure cache template.
  • Include syntax - Support include file.
  • Master layout - Support configure master layout file.
  • Extension - Support configure template file extension.
  • Easy - Support configure templates directory.
  • Auto reload - Support dynamic reload template(disable cache mode).
  • Multiple Engine - Support multiple templates for frontend and backend.
  • No external dependencies - plain ol' Go html/template.
  • Gorice - Support gorice for package resources.
  • Gin/Iris/Echo/Chi - Support gin framework, Iris framework, echo framework, go-chi framework.

Docs

See https://www.godoc.org/github.com/foolin/goview

Supports

Usage

Overview

Project structure:

|-- app/views/
    |--- index.html          
    |--- page.html
    |-- layouts/
        |--- footer.html
        |--- master.html
   

Use default instance:

    //write http.ResponseWriter
    //"index" -> index.html
    goview.Render(writer, http.StatusOK, "index", goview.M{})

Use new instance with config:

    gv := goview.New(goview.Config{
        Root:      "views",
        Extension: ".tpl",
        Master:    "layouts/master",
        Partials:  []string{"partials/ad"},
        Funcs: template.FuncMap{
            "sub": func(a, b int) int {
                return a - b
            },
            "copy": func() string {
                return time.Now().Format("2006")
            },
        },
        DisableCache: true,
	Delims:    Delims{Left: "{{", Right: "}}"},
    })
    
    //Set new instance
    goview.Use(gv)
    
    //write http.ResponseWriter
    goview.Render(writer, http.StatusOK, "index", goview.M{})

Use multiple instance with config:

    //============== Frontend ============== //
    gvFrontend := goview.New(goview.Config{
        Root:      "views/frontend",
        Extension: ".tpl",
        Master:    "layouts/master",
        Partials:  []string{"partials/ad"},
        Funcs: template.FuncMap{
            "sub": func(a, b int) int {
                return a - b
            },
            "copy": func() string {
                return time.Now().Format("2006")
            },
        },
        DisableCache: true,
	Delims:       Delims{Left: "{{", Right: "}}"},
    })
    
    //write http.ResponseWriter
    gvFrontend.Render(writer, http.StatusOK, "index", goview.M{})
    
    //============== Backend ============== //
    gvBackend := goview.New(goview.Config{
        Root:      "views/backend",
        Extension: ".tpl",
        Master:    "layouts/master",
        Partials:  []string{"partials/ad"},
        Funcs: template.FuncMap{
            "sub": func(a, b int) int {
                return a - b
            },
            "copy": func() string {
                return time.Now().Format("2006")
            },
        },
        DisableCache: true,
	Delims:       Delims{Left: "{{", Right: "}}"},
    })
    
    //write http.ResponseWriter
    gvBackend.Render(writer, http.StatusOK, "index", goview.M{})

Config

goview.Config{
    Root:      "views", //template root path
    Extension: ".tpl", //file extension
    Master:    "layouts/master", //master layout file
    Partials:  []string{"partials/head"}, //partial files
    Funcs: template.FuncMap{
        "sub": func(a, b int) int {
            return a - b
        },
        // more funcs
    },
    DisableCache: false, //if disable cache, auto reload template file for debug.
    Delims:       Delims{Left: "{{", Right: "}}"},
}

Include syntax

//template file
{{include "layouts/footer"}}

Render name:

Render name use index without .html extension, that will render with master layout.

  • "index" - Render with master layout.
  • "index.html" - Not render with master layout.
Notice: `.html` is default template extension, you can change with config

Render with master

//use name without extension `.html`
goview.Render(w, http.StatusOK, "index", goview.M{})

The w is instance of http.ResponseWriter

Render only file(not use master layout)

//use full name with extension `.html`
goview.Render(w, http.StatusOK, "page.html", goview.M{})

Custom template functions

We have two type of functions global functions, and temporary functions.

Global functions are set within the config.

goview.Config{
	Funcs: template.FuncMap{
		"reverse": e.Reverse,
	},
}
//template file
{{ reverse "route-name" }}

Temporary functions are set inside the handler.

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
	err := goview.Render(w, http.StatusOK, "index", goview.M{
		"reverse": e.Reverse,
	})
	if err != nil {
		fmt.Fprintf(w, "Render index error: %v!", err)
	}
})
//template file
{{ call $.reverse "route-name" }}

Examples

See _examples/ for a variety of examples.

Basic example

package main

import (
	"fmt"
	"github.com/foolin/goview"
	"net/http"
)

func main() {

	//render index use `index` without `.html` extension, that will render with master layout.
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		err := goview.Render(w, http.StatusOK, "index", goview.M{
			"title": "Index title!",
			"add": func(a int, b int) int {
				return a + b
			},
		})
		if err != nil {
			fmt.Fprintf(w, "Render index error: %v!", err)
		}

	})

	//render page use `page.tpl` with '.html' will only file template without master layout.
	http.HandleFunc("/page", func(w http.ResponseWriter, r *http.Request) {
		err := goview.Render(w, http.StatusOK, "page.html", goview.M{"title": "Page file title!!"})
		if err != nil {
			fmt.Fprintf(w, "Render page.html error: %v!", err)
		}
	})

	fmt.Println("Listening and serving HTTP on :9090")
	http.ListenAndServe(":9090", nil)

}

Project structure:

|-- app/views/
    |--- index.html          
    |--- page.html
    |-- layouts/
        |--- footer.html
        |--- master.html
    

See in "examples/basic" folder

Basic example

Gin example

go get github.com/foolin/goview/supports/ginview
package main

import (
	"github.com/foolin/goview/supports/ginview"
	"github.com/gin-gonic/gin"
	"net/http"
)

func main() {
	router := gin.Default()

	//new template engine
	router.HTMLRender = ginview.Default()

	router.GET("/", func(ctx *gin.Context) {
		//render with master
		ctx.HTML(http.StatusOK, "index", gin.H{
			"title": "Index title!",
			"add": func(a int, b int) int {
				return a + b
			},
		})
	})

	router.GET("/page", func(ctx *gin.Context) {
		//render only file, must full name with extension
		ctx.HTML(http.StatusOK, "page.html", gin.H{"title": "Page file title!!"})
	})

	router.Run(":9090")
}

Project structure:

|-- app/views/
    |--- index.html          
    |--- page.html
    |-- layouts/
        |--- footer.html
        |--- master.html
    

See in "examples/basic" folder

Gin example

Iris example

$ go get github.com/foolin/goview/supports/irisview
package main

import (
	"github.com/foolin/goview/supports/irisview"
	"github.com/kataras/iris/v12"
)

func main() {
	app := iris.New()

	// Register the goview template engine.
	app.RegisterView(irisview.Default())

	app.Get("/", func(ctx iris.Context) {
		// Render with master.
		ctx.View("index", iris.Map{
			"title": "Index title!",
			"add": func(a int, b int) int {
				return a + b
			},
		})
	})

	app.Get("/page", func(ctx iris.Context) {
		// Render only file, must full name with extension.
		ctx.View("page.html", iris.Map{"title": "Page file title!!"})
	})

	app.Listen(":9090")
}

Project structure:

|-- app/views/
    |--- index.html          
    |--- page.html
    |-- layouts/
        |--- footer.html
        |--- master.html
    

See in "examples/iris" folder

Iris example

Iris multiple example

package main

import (
	"html/template"
	"time"

	"github.com/foolin/goview"
	"github.com/foolin/goview/supports/irisview"
	"github.com/kataras/iris/v12"
)

func main() {
	app := iris.New()

	// Register a new template engine.
	app.RegisterView(irisview.New(goview.Config{
		Root:      "views/frontend",
		Extension: ".html",
		Master:    "layouts/master",
		Partials:  []string{"partials/ad"},
		Funcs: template.FuncMap{
			"copy": func() string {
				return time.Now().Format("2006")
			},
		},
		DisableCache: true,
	}))

	app.Get("/", func(ctx iris.Context) {
		ctx.View("index", iris.Map{
			"title": "Frontend title!",
		})
	})

	//=========== Backend ===========//

	// Assign a new template middleware.
	mw := irisview.NewMiddleware(goview.Config{
		Root:      "views/backend",
		Extension: ".html",
		Master:    "layouts/master",
		Partials:  []string{},
		Funcs: template.FuncMap{
			"copy": func() string {
				return time.Now().Format("2006")
			},
		},
		DisableCache: true,
	})

	backendGroup := app.Party("/admin", mw)

	backendGroup.Get("/", func(ctx iris.Context) {
		// Use the ctx.View as you used to. Zero changes to your codebase,
		// even if you use multiple templates.
		ctx.View("index", iris.Map{
			"title": "Backend title!",
		})
	})

	app.Listen(":9090")
}

Project structure:

|-- app/views/
    |-- fontend/
        |--- index.html
        |-- layouts/
            |--- footer.html
            |--- head.html
            |--- master.html
        |-- partials/
     	   |--- ad.html
    |-- backend/
        |--- index.html
        |-- layouts/
            |--- footer.html
            |--- head.html
            |--- master.html
        
See in "examples/iris-multiple" folder

Iris multiple example

Echo example

Echo <=v3 version:

go get github.com/foolin/goview/supports/echoview

Echo v4 version:

go get github.com/foolin/goview/supports/echoview-v4
package main

import (
	"github.com/foolin/goview/supports/echoview"
	"github.com/labstack/echo"
	"github.com/labstack/echo/middleware"
	"net/http"
)

func main() {

	// Echo instance
	e := echo.New()

	// Middleware
	e.Use(middleware.Logger())
	e.Use(middleware.Recover())

	//Set Renderer
	e.Renderer = echoview.Default()

	// Routes
	e.GET("/", func(c echo.Context) error {
		//render with master
		return c.Render(http.StatusOK, "index", echo.Map{
			"title": "Index title!",
			"add": func(a int, b int) int {
				return a + b
			},
		})
	})

	e.GET("/page", func(c echo.Context) error {
		//render only file, must full name with extension
		return c.Render(http.StatusOK, "page.html", echo.Map{"title": "Page file title!!"})
	})

	// Start server
	e.Logger.Fatal(e.Start(":9090"))
}

Project structure:

|-- app/views/
    |--- index.html          
    |--- page.html
    |-- layouts/
        |--- footer.html
        |--- master.html
    

See in "examples/basic" folder

Echo example Echo v4 example

Go-chi example

package main

import (
	"fmt"
	"github.com/foolin/goview"
	"github.com/go-chi/chi"
	"net/http"
)

func main() {

	r := chi.NewRouter()

	//render index use `index` without `.html` extension, that will render with master layout.
	r.Get("/", func(w http.ResponseWriter, r *http.Request) {
		err := goview.Render(w, http.StatusOK, "index", goview.M{
			"title": "Index title!",
			"add": func(a int, b int) int {
				return a + b
			},
		})
		if err != nil {
			fmt.Fprintf(w, "Render index error: %v!", err)
		}
	})

	//render page use `page.tpl` with '.html' will only file template without master layout.
	r.Get("/page", func(w http.ResponseWriter, r *http.Request) {
		err := goview.Render(w, http.StatusOK, "page.html", goview.M{"title": "Page file title!!"})
		if err != nil {
			fmt.Fprintf(w, "Render page.html error: %v!", err)
		}
	})

	fmt.Println("Listening and serving HTTP on :9090")
	http.ListenAndServe(":9090", r)

}

Project structure:

|-- app/views/
    |--- index.html          
    |--- page.html
    |-- layouts/
        |--- footer.html
        |--- master.html
    

See in "examples/basic" folder

Chi example

Advance example

package main

import (
	"fmt"
	"github.com/foolin/goview"
	"html/template"
	"net/http"
	"time"
)

func main() {

	gv := goview.New(goview.Config{
		Root:      "views",
		Extension: ".tpl",
		Master:    "layouts/master",
		Partials:  []string{"partials/ad"},
		Funcs: template.FuncMap{
			"sub": func(a, b int) int {
				return a - b
			},
			"copy": func() string {
				return time.Now().Format("2006")
			},
		},
		DisableCache: true,
	})

	//Set new instance
	goview.Use(gv)

	//render index use `index` without `.html` extension, that will render with master layout.
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		err := goview.Render(w, http.StatusOK, "index", goview.M{
			"title": "Index title!",
			"add": func(a int, b int) int {
				return a + b
			},
		})
		if err != nil {
			fmt.Fprintf(w, "Render index error: %v!", err)
		}

	})

	//render page use `page.tpl` with '.html' will only file template without master layout.
	http.HandleFunc("/page", func(w http.ResponseWriter, r *http.Request) {
		err := goview.Render(w, http.StatusOK, "page.tpl", goview.M{"title": "Page file title!!"})
		if err != nil {
			fmt.Fprintf(w, "Render page.html error: %v!", err)
		}
	})

	fmt.Println("Listening and serving HTTP on :9090")
	http.ListenAndServe(":9090", nil)
}

Project structure:

|-- app/views/
    |--- index.tpl          
    |--- page.tpl
    |-- layouts/
        |--- footer.tpl
        |--- head.tpl
        |--- master.tpl
    |-- partials/
        |--- ad.tpl
    

See in "examples/advance" folder

Advance example

Multiple example

package main

import (
	"html/template"
	"net/http"
	"time"

	"github.com/foolin/goview"
	"github.com/gin-gonic/gin"
)

func main() {
	router := gin.Default()

	//new template engine
	router.HTMLRender = gintemplate.New(gintemplate.TemplateConfig{
		Root:      "views/fontend",
		Extension: ".html",
		Master:    "layouts/master",
		Partials:  []string{"partials/ad"},
		Funcs: template.FuncMap{
			"copy": func() string {
				return time.Now().Format("2006")
			},
		},
		DisableCache: true,
	})

	router.GET("/", func(ctx *gin.Context) {
		// `HTML()` is a helper func to deal with multiple TemplateEngine's.
		// It detects the suitable TemplateEngine for each path automatically.
		gintemplate.HTML(ctx, http.StatusOK, "index", gin.H{
			"title": "Fontend title!",
		})
	})

	//=========== Backend ===========//

	//new middleware
	mw := gintemplate.NewMiddleware(gintemplate.TemplateConfig{
		Root:      "views/backend",
		Extension: ".html",
		Master:    "layouts/master",
		Partials:  []string{},
		Funcs: template.FuncMap{
			"copy": func() string {
				return time.Now().Format("2006")
			},
		},
		DisableCache: true,
	})

	// You should use helper func `Middleware()` to set the supplied
	// TemplateEngine and make `HTML()` work validly.
	backendGroup := router.Group("/admin", mw)

	backendGroup.GET("/", func(ctx *gin.Context) {
		// With the middleware, `HTML()` can detect the valid TemplateEngine.
		gintemplate.HTML(ctx, http.StatusOK, "index", gin.H{
			"title": "Backend title!",
		})
	})

	router.Run(":9090")
}

Project structure:

|-- app/views/
    |-- fontend/
        |--- index.html
        |-- layouts/
            |--- footer.html
            |--- head.html
            |--- master.html
        |-- partials/
     	   |--- ad.html
    |-- backend/
        |--- index.html
        |-- layouts/
            |--- footer.html
            |--- head.html
            |--- master.html
        
See in "examples/multiple" folder

Multiple example

go.rice example

go get github.com/foolin/goview/supports/gorice
package main

import (
	"fmt"
	"github.com/GeertJohan/go.rice"
	"github.com/foolin/goview"
	"github.com/foolin/goview/supports/gorice"
	"net/http"
)

func main() {

	//static
	staticBox := rice.MustFindBox("static")
	staticFileServer := http.StripPrefix("/static/", http.FileServer(staticBox.HTTPBox()))
	http.Handle("/static/", staticFileServer)

	//new view engine
	gv := gorice.New(rice.MustFindBox("views"))
	//set engine for default instance
	goview.Use(gv)

	//render index use `index` without `.html` extension, that will render with master layout.
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		err := goview.Render(w, http.StatusOK, "index", goview.M{
			"title": "Index title!",
			"add": func(a int, b int) int {
				return a + b
			},
		})
		if err != nil {
			fmt.Fprintf(w, "Render index error: %v!", err)
		}

	})

	//render page use `page.tpl` with '.html' will only file template without master layout.
	http.HandleFunc("/page", func(w http.ResponseWriter, r *http.Request) {
		err := goview.Render(w, http.StatusOK, "page.html", goview.M{"title": "Page file title!!"})
		if err != nil {
			fmt.Fprintf(w, "Render page.html error: %v!", err)
		}
	})

	fmt.Println("Listening and serving HTTP on :9090")
	http.ListenAndServe(":9090", nil)
}

Project structure:

|-- app/views/
    |--- index.html          
    |--- page.html
    |-- layouts/
        |--- footer.html
        |--- master.html
|-- app/static/  
    |-- css/
        |--- bootstrap.css   	
    |-- img/
        |--- gopher.png

See in "examples/gorice" folder

gorice example

More examples

See _examples/ for a variety of examples.

Todo

[ ] Add Partials support directory or glob [ ] Add functions support.

Issues
  • Auto complete Extensions

    Auto complete Extensions

    The file extension should not be added if it's already provided in the include instruction:

    Example:
    I use the default configuration of goview, (so the Extensions is ".html")

    error.html:

    {{define "head"}}
        {{include "style.css"}}
    {{end}}
    
    {{define "content"}}
        <h1>Error</h1>
    {{end}}
    

    style.css:

    body {
    background-color: red;
    }
    

    The error I get:

    ViewEngine execute template error: template: error:2:6: executing "head" at <include "style.css">: error calling include: ViewEngine render read name:style.css, path:<gopath>/github.com/<username>/<projectname>/service.web.oauth/views/style.css.html, error: open <gopath>/github.com/<username>/<projetctname>/service.web.oauth/views/style.css.html: no such file or directory
    
    opened by ArthurKnoep 6
  • Question about how to call a function

    Question about how to call a function

    What is the diference about calling a function with/without {{ call $.funname params }} ?

    I've been trying to add the reverse URL function to the function and it only works without call $. but I'm not sure what it's right or wrong since this is not documented

    My render

    	//Set Renderer
    	e.Renderer = echoview.New(goview.Config{
    		Root:      "app/templates",
    		Extension: ".html",
    		Master:    "layouts/master",
    		Partials:  []string{},
    		Funcs: template.FuncMap{
    			"reverse": e.Reverse,
    		},
    		DisableCache: false,
    	})
    

    This works

    {{ reverse "board_create" }}
    

    This throws an error

    {{ call $.reverse "board_create" }}
    

    Error: "ViewEngine execute template error: template: layouts/master:15:6: executing "layouts/master" at \u003cinclude "layouts/header"\u003e: error calling include: ViewEngine execute template error: template: layouts/header:15:23: executing "layouts/header" at \u003ccall $.reverse "board_create"\u003e: error calling call: call of nil"

    opened by wsantos 5
  • Context pre-processors

    Context pre-processors

    Hi I need to extract data from context and expose it to the template, mainly sure info so I can show that the user is logged in on the page header, do we have a way to do it ? do you think that maybe we can have the same functionality as Config.Funcs but they receive context? here it's my test middleware and the data I need available on all templates.

    // UserAuth -
    func (m *Middleware) UserAuth(next echo.HandlerFunc) echo.HandlerFunc {
    	return func(c echo.Context) error {
    		sess, _ := session.Get("session", c)
    		userId, _ := sess.Values["user_id"].(int)
    
    		user, _ := models.FindUser(c.Request().Context(), m.DB, userId)
    
    		c.Set("user", user)
    
    		return next(c)
    	}
    }
    

    And for echoview I think that this needs to go here, echoview.go

    // Render render template for echo interface
    func (e *ViewEngine) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
    
        // call all context processors and transform data
    
    	return e.RenderWriter(w, name, data)
    }
    

    Let me know if that is a good approach, but I'm not sure how to fit this on other frameworks.

    opened by wsantos 4
  • How can i use go.rice in gin via goview, like git-template

    How can i use go.rice in gin via goview, like git-template

    gorice and gin is work fine in foolin/gin-template

    router.HTMLRender = gorice.New(rice.MustFindBox("views"))

    but now, I will use go.rice via goview, built app throw error no such file or directory

    panic recovered:
    ViewEngine render read name:base/master, path:/tmp/templates/views/base/master.tmpl, error: open /tmp/templates/views/base/master.tmpl: no such file or directory
    

    I think go.rice is not working.

    my code:

    r := gin.Default()
    
    staticBox := rice.MustFindBox("templates/static")
    viewBox := rice.MustFindBox("templates/views")
    r.StaticFS("/static", staticBox.HTTPBox())
    
    gv := gorice.NewWithConfig(viewBox, goview.Config{
      Root:      "templates/views",
      Extension: ".tmpl",
      Master:    "base/master",
    })
    goview.Use(gv)
    
    r.HTMLRender = ginview.New(goview.Config{
      Root:      "templates/views",
      Extension: ".tmpl",
      Master:    "base/master",
    })
    
    r.GET("/", func(c *gin.Context) {
    	ginview.HTML(c, http.StatusOK, "index", gin.H{
    		"title":                  "Gin",
    		"ginBladeManagerVersion": "v1",
    		"goVersion":              runtime.Version(),
    	})
    })
    

    How do I make gorice work in gin via goview?

    opened by palytoxin 4
  • How to parse html template in to echo render?

    How to parse html template in to echo render?

    Is there any option to parse some string like "{{.Title}}"?

    Example return c.Render(http.StatusOK,index), echo.Map{"Render": "{{.Title}}"})

    opened by aigoya 3
  • Compile templates into server executable

    Compile templates into server executable

    Not sure if this is possible, but I'm trying to compile the templates/static files into the binary so that when I run the executable elsewhere, I don't also have to figure out how to ship assets - that is to say, it's all included within the compiled go binary.

    I've done this before with static assets utilizing go-bindata, but not sure if there is a way to do it for goview.

    In my case, I'm specifically utilizing goview with gin (via ginview) but hopefully that doesn't impact the answer.

    Great work btw, this package looks awesome!

    opened by josegonzalez 3
  • 我想要从子页面向 master 中定义的 menu 传值应该如何处理?

    我想要从子页面向 master 中定义的 menu 传值应该如何处理?

    目录结构:

    C:.
    │  index.html
    │  manage-posts.html
    │  write-post.html
    │  
    └─layouts
            foot.html
            head.html
            master.html
            menu.html
    

    master长这样:

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>{{.title}}</title>
        {{include "layouts/head"}}
    </head>
    <body>
        {{template "content" .}}
    </body>
    </html>
    

    menu长这样:

    <ul class="root focus">
        <li class="parent"><a href="/admin/index.php">控制台</a></li>
        <ul class="child">
            <li class="focus"><a href="/admin/">概要</a></li>
            <li><a href="/admin/profile.php">个人设置</a></li>
            <li><a href="/admin/plugins.php">插件</a></li>
            <li><a href="/admin/themes.php">外观</a></li>
            <li class="last"><a href="/admin/backup.php">备份</a></li>
        </ul>
    </ul>
    

    我想要根据当前路由动态的给menu的li加上 class="focus",请问有什么推荐的方式吗?

    opened by biuaxia 2
  • How to return html directly?

    How to return html directly?

    	html :=  goview.
    	//I want to get the html to perform string replacement operations on it, and the regular matching data, whether there is an error
    	if regexp.MustCompile(`\d{9,10}`).MatchString(html){
    		//Filter data here
    	}
    	c.HTML(200, name, _ht)
    
    opened by front-ck996 2
  • Additional funcs for templates

    Additional funcs for templates

    Hello.

    Please help with advice. I don’t understand how I can add a new function after initializing the config. For example, if we take the example "/multiple/main.go" we have two configs like gvFront and gvBackend initialized before route. How I can add a new function T into handler like:

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    		err := gvFront.Render(w, http.StatusOK, "index", goview.M{
    			"title": "Frontend title!",
                            "T": func(id string) string { return "AAAAAAAAAA!" },
    		})
    		if err != nil {
    			fmt.Fprintf(w, "Render index error: %v!", err)
    		}
    	})
    

    If we run this code, we will see an error:

    Render index error: ViewEngine render parser name:index,
    error: template: index:2: function "T" not defined!
    

    Adding a function in the process is a prerequisite, I do not need this function at the initialization stage of the config.

    opened by johndark 2
  • How i can print html comment like knockout-if

    How i can print html comment like knockout-if

    There are some js library need using comment like knockout, how i can achieve this using goview?

    <ul>
        <li>This item always appears</li>
        <!-- ko if: someExpressionGoesHere -->
            <li>I want to make this item present/absent dynamically</li>
        <!-- /ko -->
    </ul>
    
    opened by raditzlawliet 2
  • no matching versions for query

    no matching versions for query "latest"

    hi foolin! am using echov4 am run with cmd: go get -u github.com/foolin/goview/supports/echoview-v4 Error: go: finding github.com/foolin/goview/supports/echoview-v4 latest go: finding github.com/foolin/goview/supports latest go get github.com/foolin/goview/supports/echoview-v4: no matching versions for query "latest" can you help me? thanks!

    opened by thiemdp 2
  • How about partial support with `_` prefix?

    How about partial support with `_` prefix?

    Hi, I'm working on a small Go project and would like to organize my HTML files properly. For example, if there's a dashboard screen with a form and a table, I'll put the form and table in separate partial files within the same folder, prefixed with _.

    views/
    ├─ dashboard/
    ├── index.html
    ├── _table.html
    ├── _form.html
    

    And here's the way configured it

    config := goview.Config{
        ...
        Partials:  getPartialList(),
        ...
    }
    
    goview.New(config)
    
    // .....
    
    func getPartialList() []string {
    	partials := []string{}
    
    	err := filepath.Walk(ROOT_VIEW_PATH, func(path string, info fs.FileInfo, err error) error {
    		if err != nil {
    			return err
    		}
    
    		if !info.IsDir() {
    			fileName := info.Name()
    			fileExtension := filepath.Ext(fileName)
    
    			if fileExtension == ".html" && strings.HasPrefix(fileName, "_") {
    				filePath := strings.Split(path, ROOT_VIEW_PATH)[1]
    				filePathWithoutExt := filePath[:len(filePath)-len(fileExtension)]
    				partials = append(partials, filePathWithoutExt)
    			}
    		}
    
    		return nil
    	})
    
    	if err != nil {
    		log.Info("Fail to get partial files", err.Error())
    	}
    
    	return partials
    }
    

    I saw one of the open issue also mention a need for a way to configure a partial folder and I think maybe registering any HTML file prefixed with _ within the view folder might be a good idea. So I just want to propose this idea so you don't need to manually add your folder list or write a function to get all of your partial paths to be able to use them as partials.

    opened by carryall 0
  • why not support a method to dynamic clear cache ?

    why not support a method to dynamic clear cache ?

    I set the view engine DisableCache false , but I also need dynamic the clear the cache.

    can you support a method like this ?

    func (e *ViewEngine) ClearAllCache() { e.tplMutex.RLock() e.tplMap = make(map[string]*template.Template) e.tplMutex.RUnlock() } I also suggest change DisableCache to Cache ?

    opened by wzhsh90 0
  • What file structure should I create to minimize duplication of html code?

    What file structure should I create to minimize duplication of html code?

    Hi. I have such a file structure, index.html the main one, css styles and scripts are connected in it image

    the data that differ I have taken out in partials, I would like to index.html output {{template "ext" .}} or {{template "conf" .}} depending on the current page or get the parameter, is it possible to do this? Create a copy index.html , but with {{template "conf" .}} I would not like to because there can be a large number of pages

    opened by LazarenkoA 2
  • extends syntax

    extends syntax

    How hard would it be to add a extends function so we can have "multiple" masters, I need to have some pages without footer and header and right now it's set on the master layout, without it, I'll need to set footer and master on most of my pages just to have 1/2 pages without footer and master, thanks in advance.

    opened by wsantos 0
  • Embeded Static file support on golang 1.16 standard Example

    Embeded Static file support on golang 1.16 standard Example

    I see issue #9 that you have support on go.rice https://github.com/foolin/goview/issues/9 do you have plan to support go embeded or do you have example to do it? https://golang.org/pkg/embed/

    opened by golfapipol 1
Releases(v0.3.0)
Owner
foolin
foolin
A template to build dynamic web apps quickly using Go, html/template and javascript

gomodest-template A modest template to build dynamic web apps in Go, HTML and sprinkles and spots of javascript. Why ? Build dynamic websites using th

Adnaan Badr 85 Aug 10, 2022
Wrapper package for Go's template/html to allow for easy file-based template inheritance.

Extemplate Extemplate is a small wrapper package around html/template to allow for easy file-based template inheritance. File: templates/parent.tmpl <

Danny van Kooten 50 Jul 31, 2022
Fast, powerful, yet easy to use template engine for Go. Optimized for speed, zero memory allocations in hot paths. Up to 20x faster than html/template

quicktemplate A fast, powerful, yet easy to use template engine for Go. Inspired by the Mako templates philosophy. Features Extremely fast. Templates

Aliaksandr Valialkin 2.5k Aug 17, 2022
Golang Echo and html template.

golang-website-example Golang Echo and html template. move GitHub repository for hello to golang-website-example Visual Studio Code Run and Debug: lau

Ocki Bagus Pratama 0 Feb 4, 2022
Package damsel provides html outlining via css-selectors and common template functionality.

Damsel Markup language featuring html outlining via css-selectors, extensible via pkg html/template and others. Library This package expects to exist

Daniel Skinner 25 Jan 24, 2022
HTML template engine for Go

Ace - HTML template engine for Go Overview Ace is an HTML template engine for Go. This is inspired by Slim and Jade. This is a refinement of Gold. Exa

Keiji Yoshida 818 Jul 2, 2022
Simple template suitable for building a webapp backend MVP written in go

A Simple Go Project Template - Suited for Webapp MVPs A simple go project structure setup with all dependencies you need to get your MVP off the groun

El Donaldo 29 Nov 14, 2021
Api-go-template - A simple Go API template that uses a controller-service based model to build its routes

api-go-template This is a simple Go API template that uses a controller-service

Pedro Espíndula 1 Feb 18, 2022
Go-project-template - Template for a golang project

This is a template repository for golang project Usage Go to github: https://git

KyberNetwork 3 Jul 9, 2022
A Go Template Library. A bunch of utils and collections that are not part of the Golang standard library.

gotl A Go Template Library. A bunch of utils and collections that are not part of the Golang standard library. Prerequisites This library is using ext

null 1 Dec 15, 2021
Templating system for HTML and other text documents - go implementation

FAQ What is Kasia.go? Kasia.go is a Go implementation of the Kasia templating system. Kasia is primarily designed for HTML, but you can use it for any

Michał Derkacz 74 Mar 15, 2022
A strongly typed HTML templating language that compiles to Go code, and has great developer tooling.

A language, command line tool and set of IDE extensions that makes it easier to write HTML user interfaces and websites using Go.

Adrian Hesketh 131 Aug 3, 2022
Made from template temporalio/money-transfer-project-template-go

Temporal Go Project Template This is a simple project for demonstrating Temporal with the Go SDK. The full 20 minute guide is here: https://docs.tempo

MarkGorewicz 0 Jan 6, 2022
Go-api-template - A rough template to give you a starting point for your API

Golang API Template This is only a rough template to give you a starting point f

Only Tunes Radio 3 Jan 14, 2022
Safe HTML for Go

Safe HTML for Go safehtml provides immutable string-like types that wrap web types such as HTML, JavaScript and CSS. These wrappers are safe by constr

Google 280 Jul 8, 2022
mold your templated to HTML/ TEXT/ PDF easily.

mold mold your templated to HTML/ TEXT/ PDF easily. install go get github.com/mayur-tolexo/mold Example 1 //Todo model type Todo struct { Title stri

Mayur Das 0 Jun 7, 2019
starter pack for building backend with go and fiber, with jwt auth

go-fiber-api-template starter pack for building backend with go and fiber, with jwt auth authentication there are few steps for authentication steps:

Yaghoub Zargooshifar 2 Oct 12, 2021
Code your next Go web project with (a) Mojito! No matter if its an API or a website, go-mojito assists you with dependency injection, simple routing, custom request / response objects and template rendering

Go-Mojito is a super-modular library to bootstrap your next Go web project. It can be used for strict API-only purposes as well as server-side renderi

Infinytum 17 May 1, 2022
A template for the "Web Development in Go" hands-on track

go-musthave-shortener-tpl Шаблон репозитория для практического трека "Веб-разработка на Go" Начало работы Склонируйте репозиторий в любую подходящую д

null 0 Dec 29, 2021