DEV Community

Divyanshu Shekhar
Divyanshu Shekhar

Posted on • Updated on

Golang HTML Template ParseFiles and Execute

Golang HTML Template ParseFiles and Execute, parses the HTML Files, and then Execute it to allow us to display dynamic data with the help of placeholders, that can be replaced with the values at the runtime, by the template engine. The data can also be transformed according to users’ needs.

Golang Template HTML

First, create an HTML file inside the templates directory.

<!DOCTYPE html>
<html lang="en">

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Go Template</title>

    <h1>Hello, {{.Name}}</h1>
    <p>Your College name is {{.College}}</p>
    <p>Your ID is {{.RollNumber}}</p>


Enter fullscreen mode Exit fullscreen mode

The index.html file is the template that we will be using in this example. The template has three placeholders {{.Name}}, {{.College}}, and {{.RollNumber}}, whose value will be placed by the template engine at the runtime.

Golang Templates ParseFile and Execute

func renderTemplate(w http.ResponseWriter, r *http.Request) {
    student := Student{
        Name:       "GB",
        College:    "GolangBlogs",
        RollNumber: 1,
    parsedTemplate, _ := template.ParseFiles("Template/index.html")
    err := parsedTemplate.Execute(w, student)
    if err != nil {
        log.Println("Error executing template :", err)
Enter fullscreen mode Exit fullscreen mode

In the render template Function first, the student struct is initialized with values.

The Template is then parsed using the ParseFile() function from the html/template package. This creates a new template and parses the filename that is passed as input. This is not necessary to use only HTML extension, while parsing templates we can use any kind of extension like gohtml, etc.

The Parsed template is then executed and the error is handled after that.

Read whole Golang HTML Template from the original post.

Top comments (0)