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

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

define action

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

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.

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 !!

C++11/14, Qt, Juce

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store