home

A compiled template engine for Golang

22 Mar 2013

I have asked in go-nuts group that I like to have a template system that compiles to Go code. Here I will describe more about the syntax I think it should work. which I will call it gtemplate for now. There is nothing I have down to implement it yet but just show the idea.

Package of gtemplate

A gtemplate package is the same as any go package, It's just a directory inside your GOPATH

folder

The difference for example is along side the generated go source code file hello.go, there is a hello.gt file which is using different syntax but mostly similar to Golang, but gives more convenient for writing template.

Header part of gtemplate file

hello.gt:

You can see that except the func definition, All other part of the .gt file is the same as .go source, this way you can have dependency management for template files the same as go file, and you can put struct definition that will be used for template the same place as the template definition.

Template func

You can only define template inside a func, If you write { {func Hello(d *HelloData)} }, It means the method inside is mainly for output text with fewer variable replacement and loops.

A closer look at the template func definition:

What the code looks like that gtemplate generated:

It adds an argument w io.Writer to any template func, and write normal template text to the writer.

Every template func automatically added the err error return type.

Template func could be defined on data type as well:

So that you can put more commonly used variable as field into your data type.

A full gtemplate file and A full generated go source code file

What is the workflow for editing gtemplate file

I am thinking make a tool that watch all your .gt file or config your Editor to generate and compile the .go code whenever you save.

The benefit I can think of

You can go to github.com/sunfmin/gtemplate to check the progress on this.