I've template with 1 file (original file)which works as expected, now when it comes bigger I've started to divide it to 3 files
and just copy and paste the data from the original file to 3 files and I was able to see that the template was executed successfully but the data is missing in the start
and the end
template ,just the main
template receive the data properly from structData
for example
startTemple.txt
{{define "start"}}
...
{{end}}
main.txt (here i include both template)
{{template "start"}}
...
{{template "end"}}
endTemplate.txt
{{define "end"}}
...
{{end}}
I use the following
t, err := template.New(mainTemplateName).Funcs(funcMap).ParseFiles(startPath, mainPath, endPath)
err = t.Execute(templFile, structData)
if err != nil {
logs.Logger.Error(err)
}
I use the exact code as before and the issue is that the data from structData
is not appear in start
and end
template after generation, just in the main
is getting the structData properly, what could I be missing here ?
the templates (start main end) was generated successfully with the hardcoded data, but the data which should come from structData
, is not add during the generation to the start
and end
templates
Should I add the structData
also to the start
and end
somehow ?
When you use template
to invoke another template, dot
is not set by default, but you can pass the value as an (optional) second parameter to template
like this:
{{template "name" pipeline}}
In your case, your main.txt
template should be
{{template "start" .}}
...
{{template "end" .}}
to pass the value of dot
down to the start
and end
template.
Because the value of dot
can be set this way, it is also possible to split templates up into multiple files in more complex ways. For example, you could have an HTML template to display the user information in a card-style fashion, and wherever you want to insert this card in your output, you can just invoke the template and pass it the user, even when the surrounding template needs other information as well or in a loop.
For more details, check the text/template
docs. This works both for text/template
and html/template
, but is only documented explicitly for text/template
, while there is a note at the start of documentation for html/template
telling you, where the detailed documentation can be found.