dannyvankooten / extemplate

Wrapper package for Go's template/html to allow for easy file-based template inheritance.

Home Page:https://git.sr.ht/~dvko/extemplate

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

This repository moved to https://git.sr.ht/~dvko/extemplate on 2022-12-06 ⚠️


Extemplate GoDoc Build Status Go Report Card Coverage

Extemplate is a small wrapper package around html/template to allow for easy file-based template inheritance.

File: templates/parent.tmpl

<html>
<head>
	<title>{{ block "title" }}Default title{{ end }}</title>
</head>
<body>
	{{ block "content" }}Default content{{ end }} 
</body>
</html>

File: templates/child.tmpl

{{ extends "parent.tmpl" }}
{{ define "title" }}Child title{{ end }}
{{ define "content" }}Hello world!{{ end }}

File: main.go

xt := extemplate.New()
xt.ParseDir("templates/", []string{".tmpl"})
_ = xt.ExecuteTemplate(os.Stdout, "child.tmpl", "no data needed") 
// Output: <html>.... Hello world! ....</html>

Extemplate recursively walks all files in the given directory and will parse the files matching the given extensions as a template. Templates are named by path and filename, relative to the root directory.

For example, calling ParseDir("templates/", []string{".tmpl"}) on the following directory structure:

templates/
  |__ admin/
  |      |__ index.tmpl
  |      |__ edit.tmpl
  |__ index.tmpl

Will result in the following templates:

admin/index.tmpl
admin/edit.tmpl
index.tmpl

Check out the tests and examples directory for more examples.

Benchmarks

You will most likely never have to worry about performance, when using this package properly. The benchmarks are purely listed here so we have a place to keep track of progress.

BenchmarkExtemplateGetLayoutForTemplate-8   	 2000000	       923 ns/op	     104 B/op	       3 allocs/op
BenchmarkExtemplateParseDir-8               	    5000	    227898 ns/op	   34864 B/op	     325 allocs/op

License

MIT

About

Wrapper package for Go's template/html to allow for easy file-based template inheritance.

https://git.sr.ht/~dvko/extemplate

License:MIT License


Languages

Language:Go 100.0%