Golang Template-2: Template composition and how to organize template files ?

Asit Dhal
2 min readSep 17, 2016

--

Golang template library provides certain actions to make an efficient and flexible use of multiple template files.

define action

{{define "templ_name"}}second template{{end}}

Here, a template with name “templ_name” is defined.

If there multiple definitions of same template, except one, all other should be empty.

template action

{{template "templ_name" }}
{{template "templ_name" pipeline}}

Here, the template with name “templ_name” will be executed and output will be rendered at the same place.

block action

Block action is defining a template and executing in place.

{{block "name" pipeline}} huuw {{end}}

All these three actions are very powerful.

  • Template composition(nested template or template embedding or template inheritance) can be achieved.
  • Empty template can be used as placeholder templates.

How to organize template files ?

We keep our template files in two directories. One is the layout and other is the application specific views. The layout will contain base template and other common templates.

base.tmpl will contain the skeleton of HTML page for the entire website.

Now, all other templates which is a view to user. Each of these will be rendered individually.

In Go, we need to do the following.

Before the application starts to listen for HTTP request, all template files are loaded. Every time there is a request, the specific template is executed.

Working example: https://github.com/asit-dhal/golang-template-layout

Thanks for reading !!

--

--