README
Smash Golang Templating
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 |
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 ¶
- Constants
- func AddNamespacedPath(namespace Namespace, path TemplatePath)
- func ClearCache()
- func Load(file string) string
- func LoadAndParse()
- func LoadWithIdentifier(identifier, file string) string
- func RegisterFilter(identifier string, function interface{}) error
- func Set(id, content string)
- func SetPath(p TemplatePath)
- func UnregisterFilter(identifier string) error
- func UseCache(c bool)
- type Block
- type Condition
- type ConditionArgument
- type ConditionPart
- type Conditions
- type Container
- type Context
- type ForStatement
- type Namespace
- type Parser
- func (p Parser) CheckCaptureTags(content string) string
- func (p Parser) CheckCycleTags(content string) string
- func (p Parser) CheckExtends(content string) string
- func (p Parser) CheckFirstOf(content string) string
- func (p Parser) CheckForTags(content string) string
- func (p Parser) CheckIfTags(content string) string
- func (p Parser) CheckIncludes(content string) string
- func (p Parser) CheckNowTags(content string) string
- func (p Parser) CheckRaw(content string) string
- func (p Parser) CheckSetTags(content string) string
- func (p Parser) CheckSpaceless(content string) string
- func (p Parser) Clean(content string) string
- func (p Parser) Parse(content string, preseveRaw ...bool) string
- func (p Parser) RemoveComments(content string) string
- func (p Parser) ReplaceBlocks(extended, content string) string
- func (p Parser) ReplaceRaw(content string) string
- type Statement
- type Statements
- type Template
- func (t *Template) AddData(key string, data interface{})
- func (t *Template) Buffer() (b *bytes.Buffer, err error)
- func (t *Template) Bytes() []byte
- func (t *Template) GetData(key string) interface{}
- func (t *Template) Init(tpl string, ctx Context)
- func (t *Template) Parsed(preseveRaw ...bool) string
- func (t *Template) RemoveData(key string)
- func (t *Template) String() string
- func (t *Template) WriteTo(w io.Writer) (int64, error)
- type TemplatePath
- type Variable
Examples ¶
Constants ¶
const ( BYTE = 1.0 KILOBYTE = 1024 * BYTE MEGABYTE = 1024 * KILOBYTE GIGABYTE = 1024 * MEGABYTE TERABYTE = 1024 * GIGABYTE )
Definitions of file sizes
Variables ¶
Functions ¶
func AddNamespacedPath ¶
func AddNamespacedPath(namespace Namespace, path TemplatePath)
AddNamespacedPath add namespaced path which can be used in loading, including and extending templates
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 ¶
LoadWithIdentifier registers a template to the template pool
func RegisterFilter ¶
RegisterFilter registers a func to the library
func SetPath ¶
func SetPath(p TemplatePath)
SetPath sets the main template folder location. This is the first folder that is checked.
func UnregisterFilter ¶
UnregisterFilter a func to the library
Types ¶
type Condition ¶
type Condition struct {
// contains filtered or unexported fields
}
Condition type handles the template variables
type ConditionArgument ¶
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 ¶
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 (*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) 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 ¶
Container is a concurrency safe map
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 Parser ¶
type Parser struct {
// contains filtered or unexported fields
}
Parser type is the parser to parse the templates into golang templates
func (Parser) CheckCaptureTags ¶
CheckCaptureTags checks for and parses the capture tags
func (Parser) CheckCycleTags ¶
CheckCycleTags check and loads the parsed cycle tags into the template
func (Parser) CheckExtends ¶
CheckExtends check and loads the parsed includes into the template
func (Parser) CheckFirstOf ¶
CheckFirstOf check parses the tag into an if statement
func (Parser) CheckForTags ¶
CheckForTags an the blocks in the given content
func (Parser) CheckIfTags ¶
CheckIfTags checks for and interpretes the statements
func (Parser) CheckIncludes ¶
CheckIncludes check and loads the parsed includes into the template
func (Parser) CheckNowTags ¶
CheckNowTags check and parses the now tags in the templates
func (Parser) CheckSetTags ¶
CheckSetTags check and loads the parsed includes into the template
func (Parser) CheckSpaceless ¶
CheckSpaceless check and remove whitespacing and newlines between elements
func (Parser) RemoveComments ¶
RemoveComments from the template
func (Parser) ReplaceBlocks ¶
ReplaceBlocks replace blocks in the extended template if available
func (Parser) ReplaceRaw ¶
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
type Template ¶
type Template struct {
// contains filtered or unexported fields
}
Template handles the template rendering and writing to different output buffers
func NewTemplateFromString ¶
NewTemplateFromString returns a new initialised template
Example ¶
Output: Hi Smash!!!
func (*Template) RemoveData ¶
RemoveData remove the data from the template values
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
type Variable ¶
type Variable struct{}
Variable type handles the template variables
func (Variable) VarAndFilter ¶
VarAndFilter return only the variable without the filters
Source Files
Directories
Path | Synopsis |
---|---|