Have gin-gonic web app.
There are 3 files:
1) base.html -- base layout file
<!DOCTYPE html>
<html lang="en">
<body>
header...
{{template "content" .}}
footer...
</body>
</html>
2) page1.html, for /page1
{{define "content"}}
<div>
<h1>Page1</h1>
</div>
{{end}}
{{template "base.html"}}
3) page2.html, for /page2
{{define "content"}}
<div>
<h1>Page2</h1>
</div>
{{end}}
{{template "base.html"}}
The problem is that /page1 and /page2 use one template - page2.html. I think that I have misunderstanding of such constructions: {{define "content"}}, {{template "base.html"}}.
Please, can you show an example how to use base layouts in golang?
You can use the base.html as long as you parse the template along with your "content", like so:
base.html
{{define "base"}}
<!DOCTYPE html>
<html lang="en">
<body>
header...
{{template "content" .}}
footer...
</body>
</html>
{{end}}
page1.html
{{define "content"}}
I'm page 1
{{end}}
page2.html
{{define "content"}}
I'm page 2
{{end}}
then ParseFiles with ("your-page.html", "base.html"), and ExecuteTemplate with your context.
tmpl, err := template.New("").ParseFiles("page1.html", "base.html")
// check your err
err = tmpl.ExecuteTemplate(w, "base", yourContext)
Go 1.16 introduces the embed package, which packages non-.go files into binaries, greatly facilitating the deployment of Go programs. The ParseFS function was also added to the standard library html/template, which compiles all the template files contained in embed.FS into a template tree.
// templates.go
package templates
import (
"embed"
"html/template"
)
//go:embed views/*.html
var tmplFS embed.FS
type Template struct {
templates *template.Template
}
func New() *Template {
funcMap := template.FuncMap{
"inc": inc,
}
templates := template.Must(template.New("").Funcs(funcMap).ParseFS(tmplFS, "views/*.html"))
return &Template{
templates: templates,
}
}
// main.go
t := templates.New()
t.templates is a global template that contains all matching views/*.html templates, all of which are related and can be referenced to each other, and the name of the template is the name of the file, e.g. article.html.
Further, we define a Render method for the *Template type, which implements the Renderer interface of the Echo web framework.
// templates.go
func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
return t.templates.ExecuteTemplate(w, name, data)
}
You can then specify the renderer for Echo to facilitate generating HTML responses at each handler, simply by passing the name of the template to the c.Render function.
// main.go
func main() {
t := templates.New()
e := echo.New()
e.Renderer = t
}
// handler.go
func (h *Handler) articlePage(c echo.Context) error {
id := c.Param("id")
article, err := h.service.GetArticle(c.Request().Context(), id)
...
return c.Render(http.StatusOK, "article.html", article)
}
Since the t.templates template contains all the parsed templates, each template name can be used directly.
In order to assemble HTMLs, we need to use template inheritance. For example, define a layout.html for the basic HTML frame and the <head> element, and set {{block "title"}} and {{block "content"}}, other templates inherit layout.html, and populate or override the layout template's blocks of the same name with their own defined blocks.
The following is the content of the layout.html template.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{block "title" .}}{{end}}</title>
<script src="/static/main.js"></script>
</head>
<body>
<div class="main">{{block "content" .}}{{end}}</div>
</body>
</html>
For other templates, you can refer to (inherit from) layout.html and define the blocks in the layout.html template.
For example, login.html reads as follows.
{{template "layout.html" .}}
{{define "title"}}Login{{end}}
{{define "content"}}
<form class="account-form" method="post" action="/account/login" data-controller="login">
<div div="account-form-title">Login</div>
<input type="phone" name="phone" maxlength="13" class="account-form-input" placeholder="Phone" tabindex="1">
<div class="account-form-field-submit ">
<button type="submit" class="btn btn-phone">Login</button>
</div>
</form>
{{end}}
article.html also references layout.html:
{{template "layout.html" .}}
{{define "title"}}<h1>{{.Title}}</h1>{{end}}
{{define "content"}}
<p>{{.URL}}</p>
<article>{{.Content}}</article>
{{end}}
We would expect the blocks defined in the login.html template to override the blocks in layout.html when rendering it, and also when rendering the article.html template. But that's not the case, and it's down to the Go text/template implementation. In our implementation of ParseFS(tmplFS, "views/*.html"), suppose article.html is parsed first and its content block is parsed as a template name, then when the login.html template is parsed later and acontent block is also found in it, text/template will overwrite the template of the same name with the later parsed content, so when all the templates are parsed, there is actually only one template named content in our template tree, which is the content defined in the last parsed template file.
Therefore, when we execute the article.html template, it is possible that the content template is not the content defined in this template, but the content defined in other templates.
The community has proposed some solutions to this problem. For example, instead of using a global template, a new template is created each time it is rendered, containing only the contents of layout.html and the sub-template. But this is really tedious. In fact, when Go 1.6 introduced the block directive [1] for text/template, we were able to do what we wanted with the Clone method, with just a few changes to the code above.
// templates.go
package templates
import (
"embed"
"html/template"
"io"
"github.com/labstack/echo/v4"
)
//go:embed views/*.html
var tmplFS embed.FS
type Template struct {
templates *template.Template
}
func New() *Template {
funcMap := template.FuncMap{
"inc": inc,
}
templates := template.Must(template.New("").Funcs(funcMap).ParseFS(tmplFS, "views/*.html"))
return &Template{
templates: templates,
}
}
func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
tmpl := template.Must(t.templates.Clone())
tmpl = template.Must(tmpl.ParseFS(tmplFS, "views/"+name))
return tmpl.ExecuteTemplate(w, name, data)
}
You can see that only the Render function has been modified here. Instead of executing the global template, we will clone it into a new template, and the content block in this new template may not be the one we want, so here we parse the content of a sub-template we will eventually render on top of this global template, so that the content of the newly added sub-template will overwrite the previous, possibly incorrect content. Our target sub-template references layout.html in the global template, which is not conflicted, and since the global template is never executed (we clone a new global template in the Render function each time it is executed), it is also clean. When a template is finally executed, we have a clean layout.html with the content content we want, which is equivalent to generating a new template each time we execute it, which contains only the layout template and sub-templates we need. The idea is the same, but instead of manually generating a new template when executing the template, it's done automatically in the Render function.
Of course, you can also use {{ template }} to refer to other layout templates in the sub-template, as long as these layout templates do not overwrite each other, you just need to specify the name of the target sub-template when executing, and the template engine will automatically use the {{ template }} tag defined in it to find the layout templates for us, which are all in the cloned global template.
[1] https://github.com/golang/go/commit/12dfc3bee482f16263ce4673a0cce399127e2a0d
As far as I understand, when you use ParseGlob(), Gin parses all the matching files and creates a single template object from them. For doing what you want, you'd need two different templates (one for page 1, another for page 2).
Gin documentation says this is a known limitation and points the way to overcome it:
Gin allow by default use only one html.Template. Check a multitemplate render for using features like go 1.6 block template.
Using the multitemplate library, you can write something like this:
render := multitemplate.NewRenderer()
render.AddFromFiles("page1", "templates/base.html", "templates/page1.html")
render.AddFromFiles("page2", "templates/base.html", "templates/page2.html")
router := gin.Default()
router.HTMLRender = render
// Later
ginContext.HTML(200, "page1", gin.H{
"title": "The Wonderful Page One",
})
This requires more manual setup than I'd hope for, but gets the job done.
The easiest way which avoids a map and works in a single template:
base.html
<!DOCTYPE html>
<html lang="en">
<body>
header...
{{block "content" .}}{{end}}
footer...
</body>
</html>
page1.html
{{template "base.html" .}}
{{define "content"}}This is page 1{{end}}
page2.html
{{template "base.html" .}}
{{define "content"}}This is page 2{{end}}
t := template.Must(template.ParseGlob("*.html"))
err := t.ExecuteTemplate(w, "page1.html", context)
err := t.ExecuteTemplate(w, "page2.html", context)
Related
Is there any way to inject Javascript as a variable in Golang html template (html/template). I was expecting the script to be injected in the template however script is injected as string inside ".
template.html
...
<head>
{{ .myScript }}
</head>
...
parser.go
...
fp := path.Join("dir", "shop_template.html")
tmpl, err := template.ParseFiles(fp)
if err != nil {
return err
}
return tmpl.Execute(writer, myObject{Script: "<script>console.log('Hello World!');</script>"})
...
rendered html output:
...
<head>
"<script>console.log('Hello World!');</script>"
</head>
...
Expected output
<head>
<script>console.log('Hello World!');</script>
// And should log Hello World! in the console.
</head>
Assuming you are using the html/template package, this is the expected behavior. Regular strings should not be able to inject HTML/JS code.
If you trust the content, you can use template.JS or template.HTML types to inject JS and HTML code.
return tmpl.Execute(writer, myObject{
Script: template.HTML("<script>console.log('Hello World!');</script>")})
Of course, you'll need to declare:
type myObject struct {
Script template.HTML
...
}
instead of string.
If I specify a non-existent template in my template file, the error is not detected by ParseFiles() but by ExecuteTemplate(). One would expect parsing to detect any missing templates. Detecting such errors during parsing could also lead to performance improvements.
{{define "test"}}
<html>
<head>
<title> test </title>
</head>
<body>
<h1> Hello, world!</h1>
{{template "doesnotexist"}}
</body>
</html>
{{end}}
main.go
package main
import (
"html/template"
"os"
"fmt"
)
func main() {
t, err := template.ParseFiles("test.html")
if err != nil {
fmt.Printf("ParseFiles: %s\n", err)
return
}
err = t.ExecuteTemplate(os.Stdout, "test", nil)
if err != nil {
fmt.Printf("ExecuteTemplate: %s\n", err)
}
}
10:46:30 $ go run main.go
ExecuteTemplate: html/template:test.html:8:19: no such template "doesnotexist"
10:46:31 $
template.ParseFiles() doesn't report missing templates, because often not all the templates are parsed in a single step, and reporting missing templates (by template.ParseFiles()) would not allow this.
It's possible to parse templates using multiple calls, from multiple sources.
For example if you call the Template.Parse() method or your template, you can add more templates to it:
_, err = t.Parse(`{{define "doesnotexist"}}the missing piece{{end}}`)
if err != nil {
fmt.Printf("Parse failed: %v", err)
return
}
The above code will add the missing piece, and your template execution will succeed and generate the output (try it on the Go Playground):
<html>
<head>
<title> test </title>
</head>
<body>
<h1> Hello, world!</h1>
the missing piece
</body>
</html>
Going further, not requiring all templates to be parsed and "presented" gives you optimization possibilities. It's possible there are admin pages which are never used by "normal" users, and are only required if an admin user starts or uses your app. In that case you can speed up startup and same memory by not having to parse admin pages (only when / if an admin user uses your app).
See related: Go template name
Here is the problem: There are several articles on each page's content section and I'd like to insert a likebar template below each article.
So the base.tmpl is like:
<html>
<head>
{{template "head.tmpl" .}}
</head>
<body>
{{template "content.tmpl" .}}
</body>
</html>
and in article.tmpl I want to have :
{{define "content"}}
<div>article 1
{{template "likebar.tmpl" .}}
</div>
<div>article 2
{{template "likebar.tmpl" .}}
</div>
... //these divs are generated dynamically
{{end}}
How can I achieve this with html/template?
I have tried to insert a {{template "iconbar" .}} in base.tmpl and then nested {{template "likebar.tmpl" .}} inside {{define "content" but it failed with:
Template File Error: html/template:base.tmpl:122:12: no such template
"likebar.tmpl"
You can only include / insert associated templates.
If you have multiple template files, use template.ParseFiles() or template.ParseGlob() to parse them all, and the result template will have all the templates, already associated, so they can refer to each other.
If you do use the above functions to parse your templates, then the reason why it can't find likebar.tmpl is because you are referring to it by an invalid name (e.g. missing folder name).
When parsing from string source, you may use the Template.Parse() method, which also associates nested templates to the top level template.
See these 2 working examples:
func main() {
t := template.Must(template.New("").Parse(templ1))
if err := t.Execute(os.Stdout, nil); err != nil {
panic(err)
}
t2 := template.Must(template.New("").Parse(templ2))
template.Must(t2.Parse(templ2Like))
if err := t2.Execute(os.Stdout, nil); err != nil {
panic(err)
}
}
const templ1 = `Base template #1
And included one: {{template "likebar"}}
{{define "likebar"}}I'm likebar #1.{{end}}
`
const templ2 = `Base template #2
And included one: {{template "likebar"}}
`
const templ2Like = `{{define "likebar"}}I'm likebar #2.{{end}}`
Output (try it on the Go Playground):
Base template #1
And included one: I'm likebar #1.
Base template #2
And included one: I'm likebar #2.
I have been trying to use nested templates in Go, however the Examples or help documents are not helping me, and examples in 3 other blogs are not what I'm looking for (one is close and maybe the only way but I want to make sure)
OK, so my code is for App Engine, in here I will be doing an urlfetch to a server, and then I want to show some results, like the Response, headers, and body.
const statusTemplate = `
{{define "RT"}}
Status - {{.Status}}
Proto - {{.Proto}}
{{end}}
{{define "HT"}}
{{range $key, $val := .}}
{{$key}} - {{$val}}
{{end}}
{{end}}
{{define "BT"}}
{{.}}
{{end}}
{{define "MT"}}
<html>
<body>
<pre>
-- Response --
{{template "RT"}}
-- Header --
{{template "HT"}}
-- Body --
{{template "BT"}}
</pre>
</body>
</html>
{{end}}
{{template "MT"}}`
func showStatus(w http.ResponseWriterm r *http.Request) {
/*
* code to get:
* resp as http.Response
* header as a map with the header values
* body as an string wit the contents
*/
t := template.Must(template.New("status").Parse(statusTemplate)
t.ExecuteTemplate(w, "RT", resp)
t.ExecuteTemplate(w, "HT", header)
t.ExecuteTemplate(w, "BT", body)
t.Execute(w, nil)
}
My code actually outputs the RT, HT, and BT templates with the correct values, and then it outputs the MT template empty (MT stands for main template).
So... How can I use nested forms from a string variable so that an example as the above works?
I think the approach you try with nested templates is wrong. If you want . to be defined inside a nested template, you have to supply an argument to the call to the nested template, just as you do with the ExecuteTemplate function:
{{define "RT"}}
Status - {{.Status}}
Proto - {{.Proto}}
{{end}}
{{define "HT"}}
{{range $key, $val := .}}
{{$key}} - {{$val}}
{{end}}
{{end}}
{{define "BT"}}
{{.}}
{{end}}
{{define "MT"}}
<html>
<body>
<pre>
-- Response --
{{template "RT" .Resp}}
-- Header --
{{template "HT" .Header}}
-- Body --
{{template "BT" .Body}}
</pre>
</body>
</html>
{{end}}
{{template "MT"}}
The important part you seem to miss is that templates do not encapsulate state. When you execute a template, the engine evaluates the template for the given argument and then writes out the generated text. It does not save the argument or anything that was generated for future invocations.
Documentation
Relevant part of the documentation:
Actions
Here is the list of actions. "Arguments" and "pipelines" are
evaluations of data, defined in detail below.
...
{{template "name"}}
The template with the specified name is executed with nil data.
{{template "name" pipeline}}
The template with the specified name is executed with dot set
to the value of the pipeline.
...
I hope this clears up things.
have a look at this tutorial:
http://javatogo.blogspot.com
there it is explained how to use nested templates.
For example.go, I have
package main
import "html/template"
import "net/http"
func handler(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("header.html", "footer.html")
t.Execute(w, map[string] string {"Title": "My title", "Body": "Hi this is my body"})
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
In header.html:
Title is {{.Title}}
In footer.html:
Body is {{.Body}}
When going to http://localhost:8080/, I only see "Title is My title", and not the second file, footer.html. How can I load multiple files with template.ParseFiles? What's the most efficient way to do this?
Thanks in advance.
Only the first file is used as the main template. The other template files need to be included from the first like so:
Title is {{.Title}}
{{template "footer.html" .}}
The dot after "footer.html" passes the data from Execute through to the footer template -- the value passed becomes . in the included template.
There is a little shortcoming in user634175's method: the {{template "footer.html" .}} in the first template must be hard coded, which makes it difficult to change footer.html to another footer.
And here is a little improvement.
header.html:
Title is {{.Title}}
{{template "footer" .}}
footer.html:
{{define "footer"}}Body is {{.Body}}{{end}}
So that footer.html can be changed to any file that defines "footer", to make different pages