How to include nested templates from other files - go-easygen/easygen GitHub Wiki
Note: The following contents are kept for historical references.
The updated version is moved and available here
To include other Go templates from within templates, there exist a template function to be used inside template tags, which takes a “template name” and optionally a data cursor. For example:
{{ template "header" }}
Dear {{ .Name }},
Thank you for your order! Your order number is {{ .OrderNumber }} and it
has been shipped on {{ .ShipDate }}.
{{ template "footer" }}
The driving data format is simple, and can be easily guessed from the template, as shown in the nested_data.yaml file:
Name: Sam
OrderNumber: 123456
ShipDate: "Wednesday, January 06, 2021"
To put them together, use the following command, which is a short form for the equally working easygen nested_header.tmpl,nested_footer.tmpl,nested_thanks.tmpl nested_data.yaml
command:
easygen nested_header,nested_footer,nested_thanks nested_data
It'll give what is expected:
WidgetCo, Ltd.
463 Shoe Factory Rd.
Hamford, VT 20202
Dear Sam,
Thank you for your order! Your order number is 123456 and it
has been shipped on Wednesday, January 06, 2021.
2021-01-06
Thank you for your business,
WidgetCo Order Fulfillment Department
Ph: 818-555-0123 Email: [email protected]
Check out the nested_header.tmpl and nested_footer.tmpl files for more details.
Credit: the template and data are based from this blog post.
The template
action used to include nested templates also allows a second parameter to pass data to the nested template. Like the following example from here (Noticed that it was gone as of 2021-09-20, so putting my personal cache here):
// Define a nested template called header
{{define "header"}}
<h1>{{.}}</h1>
{{end}}
// Call template and pass a name parameter
{{range .Items}}
<div class="item">
{{template "header" .Name}}
<span class="price">${{.Price}}</span>
</div>
{{end}}
Example in easygen
test case ( sgdisk-emb.tmpl & sgdisk-inc.tmpl ):
$ easygen sgdisk-emb,sgdisk-inc sgdisk
sgdisk -Z /dev/sdb
sgdisk -n 0:0:+200M -t 0:ef02 -c 0:"bios_boot"
sgdisk -n 0:0:+20G -t 0:8300 -c 0:"linux_boot"
sgdisk -n 0:0:+30G -t 0:0700 -c 0:"windows"
sgdisk -n 0:0:+10G -t 0:8200 -c 0:"linux_swap"
sgdisk -n 0:0:+12G -t 0:8300 -c 0:"os1"
sgdisk -n 0:0:+12G -t 0:8300 -c 0:"os2"
sgdisk -n 0:0:+12G -t 0:8300 -c 0:"os3"
sgdisk -n 0:0:0 -t 0:8300 -c 0:"data"