A program to compile Go templates into JavaScript.
Copyright (C) 2014 Jochen Voss
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
The Go standard library provides a template language for generating HTML output in the html/template package. GoTmplJs is a program which can be used to compile Go templates into JavaScript, so that the same template can be used both for rendering the HTML version of a web page, and for rendering later updates via JavaScript. The JavaScript code generated by GoTmplJs is meant to be used with the Google Closure Tools.
warning: Implementation of GoTmplJs is not yet complete. It should work for simple templates, but it may generate invalid or wrong output in more complicated cases.
Consider the following, simple Go template:
<p>Hello, {{.}}
If we store this template in a file, say test.tmpl
, then we
can convert this template to JavaScript using the following command:
gotmpljs -n templates test.tmpl
The -n
option specifies the JavaScript name space to use for
the resulting function. The generated code is written to standard
output:
// generated by github.com/seehuhn/gotmpljs, do not edit goog.provide('templates'); goog.require('seehuhn.gotmpl'); /** * Execute the "test" template. * @param {*} data The data to apply the template to. * @return {string} The template output. */ templates.test = function(data) { var res = new Array(); res.push('<p>Hello, '); res.push(seehuhn.gotmpl.htmlescaper(data)); res.push('\n'); return res.join(''); };
The generated code depends on functions defined in the
seehuhn.gotmpl
namespace. The required code implementing
these functions is distributed as part of the GoTmplJs source code, in
the file gotmpl.js.
GoTmplJs can be installed using the go get
command:
go get github.com/seehuhn/gotmpljs