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 !!
Hacker Noon is how hackers start their afternoons. Weāre a part of the @AMIfamily. We are now accepting submissions and happy to discuss advertising &sponsorship opportunities.
To learn more, read our about page, like/message us on Facebook, or simply, tweet/DM @HackerNoon.
If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, donāt take the realities of the world for granted!