soy: Index | Files | Directories

package soy

import ""

Package soy is an implementation of Google's Closure Templates, which are data-driven templates for generating HTML.

Compared to html/template, Closure Templates have a few advantages

* Intuitive templating language that supports simple control flow, expressions and arithmetic.
* The same templates may be used from Go, Java, and Javascript.
* Internationalization is built in

and specific to this implementation:

* High performance (> 3x faster than html/template in BenchmarkSimpleTemplate)
* Hot reload for templates
* Parse a directory tree of templates

Refer to the official language spec for details:

Template example

Here is Hello World

{namespace examples.simple}

 * Says hello to the world.
{template .helloWorld}
  Hello world!

Here is a more customized version that addresses us by name and can use greetings other than "Hello".

 * Greets a person using "Hello" by default.
 * @param name The name of the person.
 * @param? greetingWord Optional greeting word to use instead of "Hello".
{template .helloName}
  {if not $greetingWord}
    Hello {$name}!
    {$greetingWord} {$name}!

This last example renders a greeting for each person in a list of names.

It demonstrates a [foreach] loop with an [ifempty] command. It also shows how to call other templates and insert their output using the [call] command. Note that the [data="all"] attribute in the call command passes all of the caller's template data to the callee template.

 * Greets a person and optionally a list of other people.
 * @param name The name of the person.
 * @param additionalNames The additional names to greet. May be an empty list.
{template .helloNames}
  // Greet the person.
  {call .helloName data="all" /}<br>
  // Greet the additional people.
  {foreach $additionalName in $additionalNames}
    {call .helloName}
      {param name: $additionalName /}
    {if not isLast($additionalName)}
      <br>  // break after every line except the last
    No additional people to greet.

This example is from

Many more examples of Soy language features/commands may be seen here:

Usage example

These are the high level steps:

* Create a soy.Bundle and add templates to it (the literal template strings,
  files, or directories).
* Compile the bundle of templates, resulting in a "Tofu" instance. It provides
  access to all your soy.
* Render a HTML template from Tofu by providing the template name and a data

Typically in a web application you have a directory containing views for all of your pages. For example:


This code snippet will parse a file of globals, all Soy templates within app/views, and provide back a Tofu intance that can be used to render any declared template. Additionally, if "mode == dev", it will watch the Soy files for changes and update your compiled templates in the background (or log compile errors to soy.Logger). Error checking is omitted.

On startup:

tofu, _ := soy.NewBundle().
    WatchFiles(true).                     // watch Soy files, reload on changes
    AddGlobalsFile("views/globals.txt").  // parse a file of globals
    AddTemplateDir("views").              // load *.soy in all sub-directories

To render a page:

var obj = map[string]interface{}{
  "user":    user,
  "account": account,
tofu.Render(resp, "acme.account.overview", obj)

Structs may be used as the data context too, but keep in mind that they are converted to data maps -- unlike html/template, the context is pure data, and you can not call methods on it.

var obj = HomepageContext{
  User:    user,
  Account: account,
tofu.Render(resp, "acme.account.overview", obj)

See soyhtml.StructOptions for knobs to control how your structs get converted to data maps.

Project Status

The goal is full compatibility and feature parity with the official Closure Templates project.

The server-side templating functionality is well tested and nearly complete, except for two notable areas: contextual autoescaping and internationalization/bidi support. Contributions welcome.

The Javascript generation is early and lacks many generation options, but it successfully passes the server-side template test suite. Note that it is possible to run the official Soy compiler to generate your javascript templates at build time, even if you use this package for server-side templates.

Please see the TODO file for features that have yet to be implemented.

Please open a Github Issue for any bugs / problems / comments, or if you find a template that renders differently than with the official compiler.


Package Files

bundle.go doc.go globals.go


var Logger = log.New(os.Stderr, "[soy] ", 0)

Logger is used to print notifications and compile errors when using the "WatchFiles" feature.

func ParseGlobals Uses

func ParseGlobals(input io.Reader) (data.Map, error)

ParseGlobals parses the given input, expecting the form:

<global_name> = <primitive_data>


- Empty lines and lines beginning with '//' are ignored.
- <primitive_data> must be a valid template expression literal for a primitive
 type (null, boolean, integer, float, or string)

type Bundle Uses

type Bundle struct {
    // contains filtered or unexported fields

Bundle is a collection of Soy content (templates and globals). It acts as input for the Soy compiler.

func NewBundle Uses

func NewBundle() *Bundle

NewBundle returns an empty bundle.

func (*Bundle) AddGlobalsFile Uses

func (b *Bundle) AddGlobalsFile(filename string) *Bundle

AddGlobalsFile opens and parses the given filename for Soy globals, and adds the resulting data map to the bundle.

func (*Bundle) AddGlobalsMap Uses

func (b *Bundle) AddGlobalsMap(globals data.Map) *Bundle

func (*Bundle) AddParsePass Uses

func (b *Bundle) AddParsePass(f func(template.Registry) error) *Bundle

AddParsePass adds a function to the bundle that will be called after the Soy is parsed.

func (*Bundle) AddTemplateDir Uses

func (b *Bundle) AddTemplateDir(root string) *Bundle

AddTemplateDir adds all *.soy files found within the given directory (including sub-directories) to the bundle.

func (*Bundle) AddTemplateFile Uses

func (b *Bundle) AddTemplateFile(filename string) *Bundle

AddTemplateFile adds the given Soy template file text to this bundle. If WatchFiles is on, it will be subsequently watched for updates.

func (*Bundle) AddTemplateString Uses

func (b *Bundle) AddTemplateString(filename, soyfile string) *Bundle

AddTemplateString adds the given template to the bundle. The name is only used for error messages - it does not need to be provided nor does it need to be a real filename.

func (*Bundle) Compile Uses

func (b *Bundle) Compile() (*template.Registry, error)

Compile parses all of the Soy files in this bundle, verifies a number of rules about data references, and returns the completed template registry.

func (*Bundle) CompileToTofu Uses

func (b *Bundle) CompileToTofu() (*soyhtml.Tofu, error)

CompileToTofu returns a soyhtml.Tofu object that allows you to render soy templates to HTML.

func (*Bundle) SetRecompilationCallback Uses

func (b *Bundle) SetRecompilationCallback(c func(*template.Registry)) *Bundle

SetRecompilationCallback assigns the bundle a function to call after recompilation. This is called before updating the in-use registry.

func (*Bundle) WatchFiles Uses

func (b *Bundle) WatchFiles(watch bool) *Bundle

WatchFiles tells Soy to watch any template files added to this bundle, re-compile as necessary, and propagate the updates to your tofu. It should be called once, before adding any files.


astPackage ast contains definitions for the in-memory representation of a Soy template.
dataPackage data contains the definitions for the Soy data types.
parsePackage parse converts a Soy template into its in-memory representation (AST)
parsepassesPackage parsepasses contains routines that validate or rewrite a Soy AST.
soyhtmlPackage soyhtml renders a compiled set of Soy to HTML.
soyjsPackage soyjs compiles Soy to javascript.
soymsg/pomsgPackage pomsg provides a PO file implementation for Soy message bundles
soymsg/pomsg/xgettext-soyxgettext-soy is a tool to extract messages from Soy templates in the PO (gettext) file format.
soywebPackage soyweb is a simple development server that serves the given template.
templatePackage template provides convenient access to groups of parsed Soy files.

Package soy imports 15 packages (graph) and is imported by 4 packages. Updated 2020-11-26. Refresh now. Tools for package owners.