README

Smash Golang Templating

codecov.io Go Report Card Build Status

Golang templating is fast and great for rendering html templates, but differs from other templating engines. Smash takes away some of the more complex configurations and restrictions. It is a simple wrapper around the Golang html/template package and is based on the Django templating syntax find documentation here (https://docs.djangoproject.com/en/1.9/ref/templates/builtins/). Most Django functionality has been ported to Golang and a list of tags and filters can be found at the end of this file. Some obscure tags and filters have been omitted from this package.

Smash adds a few functionalities and basic methods, such as extending, including, blocks and setting/changing variables in the main context.

GoDoc

Find documentation at GoDoc

Install

go get bitbucket.org/zappwork/smash

Usage

package main

import (
	"fmt"
	"time"
	"bitbucket.org/zappwork/smash"
)

func main() {
    // Smash use cache default is true. This will only work when using templates stored on disk and only for development purposes.
    smash.LoadWithIdentifier("example", "./tpl/extend.tmpl")
	ctx := smash.Context{"title": "Smash", "spacing": 3.0, "test": 10, "elements": []string{"one", "two", "three", "four"}, "Now": time.Now()}
	tpl := smash.NewTemplate("example", ctx)
	fmt.Println(tpl.Parsed())
	fmt.Println(tpl.String())
}

Smash Methods

Set template paths

Paths can take different formats and setting the main path is optional and the same is for namespaced paths.

SetPath

Set a the main template location path. This is the main location where template will be searched in.

smash.SetPath("./tests/")
tpl := smash.NewTemplate("simple-a.tmpl", smash.Context{"test": "Hello World!"})
fmt.Println(tpl.String())
Path

Returns the current main template path.

smash.SetPath("./tests")
fmt.Println(smash.Path())
AddNamespacedPath

Set a namespaced template location path. This is a namespaced template path and can be used in load, include and extending templates.

smash.AddNamespacedPath("smash", "./tests/namespace1")
tpl := smash.NewTemplate("smash:template.tmpl", nil)
fmt.Println(tpl.String())
NamespacedPath

Returns the requested namespaced template path.

smash.AddNamespacedPath("smash", "./tests/namespace1")
fmt.Println(smash.NamespacedPath("smash"))

LoadAndParse

Load and parse the template found in the path and namespaces paths. This will pre-process all templates found and will speed up initial load time. This will only have any effect if the caching is used.

smash.AddNamespacedPath("smash", "./tests/namespace1")
smash.LoadAndParse()

Set

Set a template as a string and not from file and register it to the pool.

smash.Set("id", "{{ test_var }}")
tpl := smash.NewTemplate("id", smash.Context{"test_var": "Hello World!"})
fmt.Println(tpl.String())

Load

Load a template as from file and register it to the pool.

smash.Load("./tests/simple-a.tmpl")
tpl := smash.NewTemplate("./tests/simple-a.tmpl", smash.Context{"test_var": "Hello World!"})
fmt.Println(tpl.String())

LoadWithIdentifier

Load a template as from file with and id and register it to the pool.

smash.LoadWithIdentifier("id", "./tests/simple-a.tmpl")
tpl := smash.NewTemplate("id", smash.Context{"test_var": "Hello World!"})
fmt.Println(tpl.String())

UseCache

Use caching of templates and parsed templates. During development you may want to disable caching to see the changes that were made to the templates without restarting your whole application.

// Only use for development purposes
smash.UseCache(false)

ClearCache

Clear the cache manually of all loaded and parsed templates

smash.ClearCache()

Supported Tags & Filter

Tags Filters
Supported tags Supported Filters
extends loop
block upper
include lower
comment (single & multiline) default
for default_if_none
for ... empty safe
if, elif and else concat
firstof add
spaceless length
set length_is
now addslashes
capture (multiline Go >= 1.5) capfirst
cycle (silent not implemented) center
escape
To add tags escapejs
with divisibleby
filesizeformat
Unsupported tags first
ifchanged last
load join
lorem linebreaksbr
regroup linebreaks
ssi linenumbers
templatetag ljust
url rjust
verbatim make_list
widthratio pluralize
pprint
random
slice
slugify
striptags
title
truncatechars
truncatechars_html
truncatewords
truncatewords_html
urlencode
wordcount
wordwrap
yesno
date
time
now
timeuntil
timesince
stringformat
Unsupported filters
surlize
surlizetrunc
sunordered_list
ssafeseq
sremovetags (Use striptags)
sphone2numeric
sget_digit
sforce_escape
sdictsortreversed
sdictsort
Expand ▾ Collapse ▴

Documentation

Overview

Package smash - Golang Templating Engine. Golang templating is fast and great for rendering html templates, but differs from other templating engines. Smash takes away some of the more complex configurations and restrictions. It is a simple wrapper around the Golang html/template package and is based on the Django templating syntax.

Serving templates the simple way

Serving static files is easy, see the example below.

package main

import "bitbucket.org/zappwork/smash"

func main() {
	s := `Hello {{ test }}`
	tpl := smash.NewTemplateFromString(s, smash.Context{"test": "World"})
	fmt.Println(tpl.String())
}

Index

Examples

Constants

View Source
const (
	BYTE     = 1.0
	KILOBYTE = 1024 * BYTE
	MEGABYTE = 1024 * KILOBYTE
	GIGABYTE = 1024 * MEGABYTE
	TERABYTE = 1024 * GIGABYTE
)

    Definitions of file sizes

    Variables

    This section is empty.

    Functions

    func AddNamespacedPath

    func AddNamespacedPath(namespace Namespace, path TemplatePath)

      AddNamespacedPath add namespaced path which can be used in loading, including and extending templates

      func ClearCache

      func ClearCache()

        ClearCache clears the cache of parsed and loaded templates

        func Load

        func Load(file string) string

          Load registers a template to the template pool

          func LoadAndParse

          func LoadAndParse()

            LoadAndParse loads and parses all templates found in the path and namespaced paths. This will increase performance and check all templates when they are parsed

            func LoadWithIdentifier

            func LoadWithIdentifier(identifier, file string) string

              LoadWithIdentifier registers a template to the template pool

              func RegisterFilter

              func RegisterFilter(identifier string, function interface{}) error

                RegisterFilter registers a func to the library

                func Set

                func Set(id, content string)

                  Set registers a template and content to the template pool

                  func SetPath

                  func SetPath(p TemplatePath)

                    SetPath sets the main template folder location. This is the first folder that is checked.

                    func UnregisterFilter

                    func UnregisterFilter(identifier string) error

                      UnregisterFilter a func to the library

                      func UseCache

                      func UseCache(c bool)

                        UseCache enables/disables caching of the load/parsed templates. during development of the templates it can be useful to turn of caching.

                        Types

                        type Block

                        type Block struct {
                        	Initial string
                        	ID      string
                        	Content string
                        }

                          Block type is definition of a block

                          type Condition

                          type Condition struct {
                          	// contains filtered or unexported fields
                          }

                            Condition type handles the template variables

                            func NewCondition

                            func NewCondition() Condition

                              NewCondition return a variable type

                              func (*Condition) Init

                              func (c *Condition) Init()

                                Init condition type

                                func (Condition) Parse

                                func (c Condition) Parse(s string) string

                                  Parse the condition to a golang template condition

                                  type ConditionArgument

                                  type ConditionArgument struct {
                                  	Value string
                                  	Not   bool
                                  }

                                    ConditionArgument type is an argument of the condition

                                    func (ConditionArgument) ToString

                                    func (ca ConditionArgument) ToString() string

                                      ToString return a string representation to the condition argument

                                      type ConditionPart

                                      type ConditionPart struct {
                                      	Operator string
                                      	Not      bool
                                      	// contains filtered or unexported fields
                                      }

                                        ConditionPart type is part of condition

                                        func (*ConditionPart) AddArgument

                                        func (cp *ConditionPart) AddArgument(c string, notEquals bool)

                                          AddArgument add condtion to the condition part

                                          func (*ConditionPart) Complete

                                          func (cp *ConditionPart) Complete() bool

                                            Complete is the condition complete and nothing can be added

                                            func (*ConditionPart) Empty

                                            func (cp *ConditionPart) Empty() bool

                                              Empty returns if the object is empty

                                              func (*ConditionPart) ToString

                                              func (cp *ConditionPart) ToString() string

                                                ToString return a string representation to the condition part

                                                type Conditions

                                                type Conditions struct {
                                                	// contains filtered or unexported fields
                                                }

                                                  Conditions holds all the sub conditions

                                                  func NewConditions

                                                  func NewConditions() Conditions

                                                    NewConditions return a variable type

                                                    func (*Conditions) AddArgument

                                                    func (c *Conditions) AddArgument(a string, notEquals bool)

                                                      AddArgument add condtion to the condition part

                                                      func (*Conditions) AddOperator

                                                      func (c *Conditions) AddOperator(o string)

                                                        AddOperator add operator to the condition part

                                                        func (*Conditions) Init

                                                        func (c *Conditions) Init()

                                                          Init the conditions holder

                                                          func (*Conditions) SetNotEquals

                                                          func (c *Conditions) SetNotEquals(not bool)

                                                            SetNotEquals the condition should not equal the outcome

                                                            func (*Conditions) ToString

                                                            func (c *Conditions) ToString() string

                                                              ToString return a string representation to the condition part

                                                              type Container

                                                              type Container struct {
                                                              	sync.RWMutex
                                                              	// contains filtered or unexported fields
                                                              }

                                                                Container is a concurrency safe map

                                                                func NewContainer

                                                                func NewContainer() *Container

                                                                  NewContainer creates a new container

                                                                  func (*Container) Get

                                                                  func (c *Container) Get(key string) string

                                                                    Get the item from the container with the given key

                                                                    func (*Container) Has

                                                                    func (c *Container) Has(key string) bool

                                                                      Has the container a value with the given key

                                                                      func (*Container) Remove

                                                                      func (c *Container) Remove(key string)

                                                                        Remove the item from the container with the given key

                                                                        func (*Container) Reset

                                                                        func (c *Container) Reset()

                                                                          Reset the container

                                                                          func (*Container) Set

                                                                          func (c *Container) Set(key, value string)

                                                                            Set the item in the container with the given key

                                                                            type Context

                                                                            type Context map[string]interface{}

                                                                              Context is the type that holds the data

                                                                              type ForStatement

                                                                              type ForStatement struct {
                                                                              	Initial   string
                                                                              	Content   string
                                                                              	New       string
                                                                              	Statement string
                                                                              	Key       string
                                                                              	Value     string
                                                                              	Var       string
                                                                              	Start     int
                                                                              	End       int
                                                                              }

                                                                                ForStatement model

                                                                                func (ForStatement) NewStatement

                                                                                func (f ForStatement) NewStatement(replaceGlobals bool) string

                                                                                  NewStatement returns the for loop as needs to be in go templates

                                                                                  type Namespace

                                                                                  type Namespace string

                                                                                    Namespace is a template path namespace

                                                                                    type Parser

                                                                                    type Parser struct {
                                                                                    	// contains filtered or unexported fields
                                                                                    }

                                                                                      Parser type is the parser to parse the templates into golang templates

                                                                                      func NewParser

                                                                                      func NewParser() Parser

                                                                                        NewParser returns a new Parser

                                                                                        func (Parser) CheckCaptureTags

                                                                                        func (p Parser) CheckCaptureTags(content string) string

                                                                                          CheckCaptureTags checks for and parses the capture tags

                                                                                          func (Parser) CheckCycleTags

                                                                                          func (p Parser) CheckCycleTags(content string) string

                                                                                            CheckCycleTags check and loads the parsed cycle tags into the template

                                                                                            func (Parser) CheckExtends

                                                                                            func (p Parser) CheckExtends(content string) string

                                                                                              CheckExtends check and loads the parsed includes into the template

                                                                                              func (Parser) CheckFirstOf

                                                                                              func (p Parser) CheckFirstOf(content string) string

                                                                                                CheckFirstOf check parses the tag into an if statement

                                                                                                func (Parser) CheckForTags

                                                                                                func (p Parser) CheckForTags(content string) string

                                                                                                  CheckForTags an the blocks in the given content

                                                                                                  func (Parser) CheckIfTags

                                                                                                  func (p Parser) CheckIfTags(content string) string

                                                                                                    CheckIfTags checks for and interpretes the statements

                                                                                                    func (Parser) CheckIncludes

                                                                                                    func (p Parser) CheckIncludes(content string) string

                                                                                                      CheckIncludes check and loads the parsed includes into the template

                                                                                                      func (Parser) CheckNowTags

                                                                                                      func (p Parser) CheckNowTags(content string) string

                                                                                                        CheckNowTags check and parses the now tags in the templates

                                                                                                        func (Parser) CheckRaw

                                                                                                        func (p Parser) CheckRaw(content string) string

                                                                                                          CheckRaw check for raw tags and replace with placeholders

                                                                                                          func (Parser) CheckSetTags

                                                                                                          func (p Parser) CheckSetTags(content string) string

                                                                                                            CheckSetTags check and loads the parsed includes into the template

                                                                                                            func (Parser) CheckSpaceless

                                                                                                            func (p Parser) CheckSpaceless(content string) string

                                                                                                              CheckSpaceless check and remove whitespacing and newlines between elements

                                                                                                              func (Parser) Clean

                                                                                                              func (p Parser) Clean(content string) string

                                                                                                              func (Parser) Parse

                                                                                                              func (p Parser) Parse(content string, preseveRaw ...bool) string

                                                                                                                Parse the given content. The function panics if the content cannot be parsed.

                                                                                                                func (Parser) RemoveComments

                                                                                                                func (p Parser) RemoveComments(content string) string

                                                                                                                  RemoveComments from the template

                                                                                                                  func (Parser) ReplaceBlocks

                                                                                                                  func (p Parser) ReplaceBlocks(extended, content string) string

                                                                                                                    ReplaceBlocks replace blocks in the extended template if available

                                                                                                                    func (Parser) ReplaceRaw

                                                                                                                    func (p Parser) ReplaceRaw(content string) string

                                                                                                                      ReplaceRaw check parses raw tags into escape string tags

                                                                                                                      type Statement

                                                                                                                      type Statement struct {
                                                                                                                      	Start      int
                                                                                                                      	End        int
                                                                                                                      	Content    string
                                                                                                                      	Statements Statements
                                                                                                                      }

                                                                                                                        Statement containing the statement

                                                                                                                        func NewStatement

                                                                                                                        func NewStatement() *Statement

                                                                                                                          NewStatement returns a pointer to a Statement

                                                                                                                          func (*Statement) Add

                                                                                                                          func (stm *Statement) Add(s *Statement)

                                                                                                                            Add the statement to the current statement or sub statements

                                                                                                                            func (*Statement) Parse

                                                                                                                            func (stm *Statement) Parse(content string) string

                                                                                                                              Parse the given content

                                                                                                                              func (*Statement) String

                                                                                                                              func (stm *Statement) String() string

                                                                                                                                String return a string repesentation of parse content

                                                                                                                                type Statements

                                                                                                                                type Statements []*Statement

                                                                                                                                  Statements container for statement's

                                                                                                                                  type Template

                                                                                                                                  type Template struct {
                                                                                                                                  	// contains filtered or unexported fields
                                                                                                                                  }

                                                                                                                                    Template handles the template rendering and writing to different output buffers

                                                                                                                                    func NewTemplate

                                                                                                                                    func NewTemplate(tpl string, ctx Context) Template

                                                                                                                                      NewTemplate returns a new initialised template

                                                                                                                                      Example
                                                                                                                                      Output:
                                                                                                                                      
                                                                                                                                      Hello World
                                                                                                                                      

                                                                                                                                      func NewTemplateFromString

                                                                                                                                      func NewTemplateFromString(s string, ctx Context) Template

                                                                                                                                        NewTemplateFromString returns a new initialised template

                                                                                                                                        Example
                                                                                                                                        Output:
                                                                                                                                        
                                                                                                                                        Hi Smash!!!
                                                                                                                                        

                                                                                                                                        func (*Template) AddData

                                                                                                                                        func (t *Template) AddData(key string, data interface{})

                                                                                                                                          AddData add data to the template values

                                                                                                                                          func (*Template) Buffer

                                                                                                                                          func (t *Template) Buffer() (b *bytes.Buffer, err error)

                                                                                                                                            Buffer returns the parsed bytes.Buffer of the given template

                                                                                                                                            func (*Template) Bytes

                                                                                                                                            func (t *Template) Bytes() []byte

                                                                                                                                              Bytes returns the parsed byte slice of the given template

                                                                                                                                              func (*Template) GetData

                                                                                                                                              func (t *Template) GetData(key string) interface{}

                                                                                                                                                GetData get data to the template values

                                                                                                                                                func (*Template) Init

                                                                                                                                                func (t *Template) Init(tpl string, ctx Context)

                                                                                                                                                  Init the template type

                                                                                                                                                  func (*Template) Parsed

                                                                                                                                                  func (t *Template) Parsed(preseveRaw ...bool) string

                                                                                                                                                    Parsed get the parsed raw unrendered template string

                                                                                                                                                    func (*Template) RemoveData

                                                                                                                                                    func (t *Template) RemoveData(key string)

                                                                                                                                                      RemoveData remove the data from the template values

                                                                                                                                                      func (*Template) String

                                                                                                                                                      func (t *Template) String() string

                                                                                                                                                        String returns the parsed string of the given template

                                                                                                                                                        func (*Template) WriteTo

                                                                                                                                                        func (t *Template) WriteTo(w io.Writer) (int64, error)

                                                                                                                                                          WriteTo writes bytes to a writer interface

                                                                                                                                                          type TemplatePath

                                                                                                                                                          type TemplatePath string

                                                                                                                                                            TemplatePath is a template path

                                                                                                                                                            func NamespacedPath

                                                                                                                                                            func NamespacedPath(namespace Namespace) TemplatePath

                                                                                                                                                              NamespacedPath return the template path for the given namespace The method return nil if no path was found

                                                                                                                                                              func Path

                                                                                                                                                              func Path() TemplatePath

                                                                                                                                                                Path returns the main template path folder

                                                                                                                                                                type Variable

                                                                                                                                                                type Variable struct{}

                                                                                                                                                                  Variable type handles the template variables

                                                                                                                                                                  func NewVariable

                                                                                                                                                                  func NewVariable() Variable

                                                                                                                                                                    NewVariable return a variable type

                                                                                                                                                                    func (Variable) Clean

                                                                                                                                                                    func (v Variable) Clean(s string) string

                                                                                                                                                                      Clean cleans var name to a go like template var

                                                                                                                                                                      func (Variable) Escape

                                                                                                                                                                      func (v Variable) Escape(s string) string

                                                                                                                                                                        Escape the given input

                                                                                                                                                                        func (Variable) Parse

                                                                                                                                                                        func (v Variable) Parse(s string) string

                                                                                                                                                                          Parse the variable to a golang template var

                                                                                                                                                                          func (Variable) Unescape

                                                                                                                                                                          func (v Variable) Unescape(s string) string

                                                                                                                                                                            Unescape the given output

                                                                                                                                                                            func (Variable) Var

                                                                                                                                                                            func (v Variable) Var(s string) string

                                                                                                                                                                              Var return only the variable without the filters

                                                                                                                                                                              func (Variable) VarAndFilter

                                                                                                                                                                              func (v Variable) VarAndFilter(s string) string

                                                                                                                                                                                VarAndFilter return only the variable without the filters

                                                                                                                                                                                Directories

                                                                                                                                                                                Path Synopsis