Handlebars for golang
⚠️ Project is archived ⚠️
Handlebars for golang with the same features as handlebars.js 3.0.
The full API documentation is available here: .
$ go get github.com/aymerick/raymondThe quick and dirty way of rendering a handlebars template:
package main
import (
"fmt"
"github.com/aymerick/raymond"
)
func main() {
tpl := `
`
ctx := map[string]string{
"title": "My New Post",
"body": "This is my first post!",
}
result, err := raymond.Render(tpl, ctx)
if err != nil {
panic("Please report a bug :)")
}
fmt.Print(result)
}Displays:
Please note that the template will be parsed everytime you call Render() function. So you probably want to read the next section.
To avoid parsing a template several times, use the Parse() and Exec() functions:
…Displays:
You can use MustParse() and MustExec() functions if you don't want to deal with errors:
// parse template
tpl := raymond.MustParse(source)
// render template
result := tpl.MustExec(ctx)The rendering context can contain any type of values, including array, slice, map, struct and func.
When using structs, be warned that only exported fields are accessible. However you can access exported fields in template with their lowercase names. For example, both {{author.firstName}} and {{Author.FirstName}} references give the same result, as long as Author and FirstName are exported struct fields.
More, you can use the handlebars struct tag to specify a template variable name different from the struct field name.
…Output:
Comments
By Marcel Beliveau
By default, the result of a mustache expression is HTML escaped. Use the triple mustache {{{ to output unescaped values.
source := `
`
ctx := map[string]string{
"title": "All about
Tags",
"body": "
This is a post about <p> tags
",
}
tpl := raymond.MustParse(source)
result := tpl.MustExec(ctx)
fmt.Print(result)Output:
When returning HTML from a helper, you should return a SafeString if you don't want it to be escaped by default. When using SafeString all unknown or unsafe data should be manually escaped with the Escape method.
raymond.RegisterHelper("link", func(url, text string) raymond.SafeString {
return raymond.SafeString("" + raymond.Escape(text) + "")
})
tpl := raymond.MustParse("{{link url text}}")
ctx := map[string]string{
"url": "http://www.aymerick.com/",
"text": "This is a cool website",
}
result := tpl.MustExec(ctx)
fmt.Print(result)Output:
This is a <em>cool</em> websiteHelpers can be accessed from any context in a template. You can register a helper with the RegisterHelper function.
For example:
Comments
{{#each comments}}
By {{fullName author}}
{{/each}}
With this context and helper:
ctx := map[string]interface{}{
"author": map[string]string{"firstName": "Jean", "lastName": "Valjean"},
"body": "Life is difficult",
"comments": []map[string]interface{}{{
"author": map[string]string{"firstName": "Marcel", "lastName": "Beliveau"},
"body": "LOL!",
}},
}
raymond.RegisterHelper("fullName", func(person map[string]string) string {
return person["firstName"] + " " + person["lastName"]
})Outputs:
Comments
By Marcel Beliveau
Helper arguments can be any type.
The following example uses structs instead of maps and produces the same output as the previous one:
Comments
{{#each comments}}
By {{fullName author}}
{{/each}}
With this context and helper:
type Post struct {
Author Person
Body string
Comments []Comment
}
type Person struct {
FirstName string
LastName string
}
type Comment struct {
Author Person
Body string
}
ctx := Post{
Person{"Jean", "Valjean"},
"Life is difficult",
[]Comment{
Comment{
Person{"Marcel", "Beliveau"},
"LOL!",
},
},
}
raymond.RegisterHelper("fullName", func(person Person) string {
return person.FirstName + " " + person.LastName
})You can unregister global helpers with RemoveHelper and RemoveAllHelpers functions:
raymond.RemoveHelper("fullname")raymond.RemoveAllHelpers()You can register a helper on a specific template, and in that case that helper will be available to that template only:
tpl := raymond.MustParse("User: {{fullName user.firstName user.lastName}}")
tpl.RegisterHelper("fullName", func(firstName, lastName string) string {
return firstName + " " + lastName
})Those built-in helpers are available to all templates.
if block helperYou can use the if helper to conditionally render a block. If its argument returns false, nil, 0, "", an empty array, an empty slice or an empty map, then raymond will not render the block.
When using a block expression, you can specify a template section to run if the expression returns a falsy value. That section, marked by {{else}} is called an "else section".
You can chain several blocks. For example that template:
{{#if isActive}}
{{else if isInactive}}
{{else}}
{{/if}}With that context:
ctx := map[string]interface{}{
"isActive": false,
"isInactive": false,
}Outputs:
unless block helperYou can use the unless helper as the inverse of the if helper. Its block will be rendered if the expression returns a falsy value.
each block helperYou can iterate over an array, a slice, a map or a struct instance using this built-in each helper. Inside the block, you can use this to reference the element being iterated over.
For example:
{{#each people}}
{{this}}
{{/each}}
With this context:
map[string]interface{}{
"people": []string{
"Marcel", "Jean-Claude", "Yvette",
},
}Outputs:
Marcel
Jean-Claude
Yvette
You can optionally provide an {{else}} section which will display only when the passed argument is an empty array, an empty slice or an empty map (a struct instance is never considered empty).
{{#each paragraphs}}
{{this}}
{{else}}
No content
{{/each}}When looping through items in each, you can optionally reference the current loop index via {{@index}}.
{{#each array}}
{{@index}}: {{this}}
{{/each}}Additionally for map and struct instance iteration, {{@key}} references the current map key or struct field name:
{{#each map}}
{{@key}}: {{this}}
{{/each}}The first and last steps of iteration are noted via the @first and @last variables.
with block helperYou can shift the context for a section of a template by using the built-in with block helper.
With this context:
map[string]interface{}{
"title": "My first post!",
"author": map[string]string{
"firstName": "Jean",
"lastName": "Valjean",
},
}Outputs:
You can optionally provide an {{else}} section which will display only when the passed argument is falsy.
{{#with author}}
{{name}}
{{else}}
No content
{{/with}}lookup helperThe lookup helper allows for dynamic parameter resolution using handlebars variables.
{{#each bar}}
{{lookup ../foo @index}}
{{/each}}log helperThe log helper allows for logging while rendering a template.
{{log "Look at me!"}}Note that the handlebars.js @level variable is not supported.
equal helperThe equal helper renders a block if the string version of both arguments are equals.
For example that template:
{{#equal foo "bar"}}foo is bar{{/equal}}
{{#equal foo baz}}foo is the same as baz{{/equal}}
{{#equal nb 0}}nothing{{/equal}}
{{#equal nb 1}}there is one{{/equal}}
{{#equal nb "1"}}everything is stringified before comparison{{/equal}}With that context:
ctx := map[string]interface{}{
"foo": "bar",
"baz": "bar",
"nb": 1,
}Outputs:
foo is bar
foo is the same as baz
there is one
everything is stringified before comparisonBlock helpers make it possible to define custom iterators and other functionality that can invoke the passed block with a new context.
As an example, let's define a block helper that adds some markup to the wrapped text.
The bold helper will add markup to make its text bold.
raymond.RegisterHelper("bold", func(options *raymond.Options) raymond.SafeString {
return raymond.SafeString(`
")
})A helper evaluates the block content with current context by calling options.Fn().
If you want to evaluate the block with another context, then use options.FnWith(ctx), like this french version of built-in with block helper:
raymond.RegisterHelper("avec", func(context interface{}, options *raymond.Options) string {
return options.FnWith(context)
})With that template:
{{#avec obj.text}}{{this}}{{/avec}}Let's write a french version of if block helper:
source := `{{#si yep}}YEP !{{/si}}`
ctx := map[string]interface{}{"yep": true}
raymond.RegisterHelper("si", func(conditional bool, options *raymond.Options) string {
if conditional {
return options.Fn()
}
return ""
})Note that as the first parameter of the helper is typed as bool an automatic conversion is made if corresponding context value is not a boolean. So this helper works with that context too:
ctx := map[string]interface{}{"yep": "message"}Here, "message" is converted to true because it is an non-empty string
No open issues yet, or sync has not completed.