To use Scriggo as a template engine, use scriggo.BuildTemplate to compile a specific file from a scriggo.Files filesystem. You can pass BuildOptions to define global variables and functions (using native.Declarations) that will be available within the template. Once built, use template.Run to render the template to an io.Writer.
// Build and run a Scriggo template.
package main
import (
"os"
"github.com/open2b/scriggo"
"github.com/open2b/scriggo/builtin"
"github.com/open2b/scriggo/native"
)
func main() {
// Content of the template file to run.
content := []byte(`
<!DOCTYPE html>
<html>
<head>Hello</head>
<body
Hello, {{ capitalize(who) }}!
</body>
</html>
`)
// Create a file system with the file of the template to run.
fsys := scriggo.Files{"index.html": content}
// Declare some globals.
var who = "world"
opts := &scriggo.BuildOptions{
Globals: native.Declarations{
"who": &who, // global variable
"capitalize": builtin.Capitalize, // global function
},
}
// Build the template.
template, err := scriggo.BuildTemplate(fsys, "index.html", opts)
if err != nil {
panic(err)
}
// Run the template and print it to the standard output.
err = template.Run(os.Stdout, nil, nil)
if err != nil {
panic(err)
}
}