Html/template layout and content file

I have written my handler to parse the layout file and the content file

func homeHandler(w http.ResponseWriter, r *http.Request) {
	tmpl, err := template.ParseFiles("ui/templates/layouts/layout.html", "ui/templates/index.html")
	if err != nil {
		panic(err)
	}
	tmpl.ExecuteTemplate(w, "layout.html", nil)
}

My layout.html looks like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    {{template "content" .}}
</body>
</html>

and index.html files looks as follows:

{{define "content"}}
<h1>This is the index Page</h1>
{{end}}

My question is: Is it a good practice to parse files every time I call the handler, is there another way to achieve a layout & content style?

1 Like

Depends on your deployment resources. If memories are largely available and the static files (html etc.) are not always changing, you can cache it onto memory the first time you parse.

Otherwise, you can embed into the go binary itself using library like packr and functionalize them for optimum memory management. The drawback is that the binary is usually very large (>100MB) per last experience. The good side is that you had achieve dependency-free in this mode.

Otherwise, parsing is fine. If you need a reference, Hugo is a good example.

2 Likes

Are you saying hugo parses files for every request?

2 Likes

Hugo parse and build the static contents once.

I’m referring to how they work on parser, structures, etc.

EDIT:

One good example is their theme module system that successfully separate templates in multiple aspects and “shortcodes” plugin to simplify upper level rendering codes.

Another good example is the split parsing (as in locally and from the theme repository). That way, designers only deal with the HTML parts while leaving your go codes in tact.

If you’re creating a fully compatible parser, you can re-use all the available Hugo themes which saves a lot of time on design codes.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.