Learn Fiber · 8/14

Views and Template Rendering

8 min read

Welcome to the wonderful world of server-side rendering with Fiber! If you've ever wanted to build dynamic web pages without drowning in a sea of client-side JavaScript frameworks, you've come to the right place. We're going to explore how Fiber makes it a breeze to serve up beautiful, data-driven HTML.

The Problem: How do you create web pages that change based on user data or other information? You could try stringing together HTML in your Go code, but that gets messy faster than a toddler with a bowl of spaghetti. 🍝

The Solution: Template engines! These are tools that let you write HTML with special placeholders for your dynamic data. Your Go code then "renders" these templates, replacing the placeholders with real data before sending the final HTML to the user's browser. It's like having a fill-in-the-blanks storybook for your web pages.


1. Introduction to Fiber Template Engines

Fiber itself is a lean, mean, routing machine. It doesn't come with a built-in template engine. Why? To give you, the developer, the freedom to choose the one that best fits your needs (or your team's existing skills).

Imagine you're building a house. Fiber lays the foundation and framework. For the interior design (the part the user sees), you can hire any designer you like—a minimalist, a modernist, or someone who loves glitter on everything. ✨

Fiber supports a wide variety of template engines through its template middleware. Some popular choices include:

  • html: The standard Go html/template package. It's built-in, secure, and a great starting point.
  • Handlebars: Known for its simple, logic-less syntax.
  • Pug (formerly Jade): Uses indentation to create clean, readable templates.
  • Amber: Another powerful engine that compiles to optimized Go code.
  • And many more like Ace, Django, Jet, Mustache, and Slim!

For this guide, we'll focus on the standard Go html/template engine because it's the most common and a fantastic way to learn the core concepts.

Getting Started: Setting up a Template Engine

First things first, let's get our project set up.

  1. Initialize your Go project:

    bash
    mkdir fiber-views-guide
    cd fiber-views-guide
    go mod init example.com/fiber-views-guide
  2. Install Fiber and the HTML template engine package:

    bash
    go get github.com/gofiber/fiber/v3
    go get github.com/gofiber/template/html/v3
  3. Create a views directory: This is where we'll store our HTML template files.

    bash
    mkdir views

Now, let's configure our Fiber app to use the HTML engine. In your main.go, you'll initialize the engine and pass it to the Fiber app configuration.

go
package main

import (
	"log"

	"github.com/gofiber/fiber/v3"
	"github.com/gofiber/template/html/v3"
)

func main() {
	// Initialize a new HTML template engine
	engine := html.New("./views", ".html")

	// Create a new Fiber app with the template engine
	app := fiber.New(fiber.Config{
		Views: engine,
	})

	app.Get("/", func(c fiber.Ctx) error {
		// We'll render a template here soon!
		return c.SendString("Setup complete! 🎉")
	})

	log.Fatal(app.Listen(":3000"))
}

When you create a new engine with html.New("./views", ".html"), you're telling Fiber two things:

  1. Look for my template files in the ./views directory.
  2. My template files will have the .html extension.

Simple, right? Now our app knows where to find its "blueprints" for the pages we want to create.


2. Rendering Standard Go HTML Templates

Now that our engine is configured, let's actually render a page. This is where the magic happens!

The Problem: We have an HTML file, and we need our Fiber server to send it to the user when they visit a specific route.

The Solution: The c.Render() method. This function is your gateway to rendering templates. It takes the name of the template file and some data to pass to it (we'll cover that in the next section).

Let's create our first template. Inside the views directory, create a file named index.html:

views/index.html

html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My First Fiber App</title>
</head>
<body>
    <h1>Welcome to the World of Fiber Templates!</h1>
    <p>This page was rendered by our awesome Go server.</p>
</body>
</html>

Now, let's update our main.go to render this template.

go
// ... (imports and main function setup from before)

app.Get("/", func(c fiber.Ctx) error {
    // Render the "index" template
    // The second argument is for data, which is nil for now.
    return c.Render("index", nil)
})

// ... (log.Fatal from before)

Run your application (go run main.go) and navigate to http://localhost:3000. You should see your beautiful HTML page! 🥳

What just happened?

  1. The browser sent a GET request to /.
  2. Fiber matched the route and executed our handler function.
  3. c.Render("index", nil) told the HTML engine to find a file named index.html inside the views directory.
  4. The engine read the file and sent its contents as the HTTP response.

Funny Fact: Forgetting to pass nil as the second argument to Render when you have no data is a common rite of passage for new Fiber developers. The Go compiler will give you a gentle (or not-so-gentle) reminder.


3. Passing Dynamic Data to Views

Static pages are great, but the real power of templates comes from injecting dynamic data.

The Problem: How do we show user-specific information, like a welcome message with their name, or a list of products from a database?

The Solution: The second argument of c.Render(). We can pass data to our templates using a fiber.Map. Think of fiber.Map as a dictionary or a key-value store where the keys are strings you'll use in your template.

Let's update our handler to pass some data:

go
// ...

app.Get("/", func(c fiber.Ctx) error {
    // Render the "index" template with some data
    return c.Render("index", fiber.Map{
        "Title":   "Hello, Friend!",
        "Content": "This is dynamic content passed from our Go server.",
    })
})

// ...

Now, we need to update our index.html to use this data. In Go templates, you use {{ . }} to access the data you passed in. The dot (.) represents the data object (fiber.Map in our case). You can access its fields with {{ .FieldName }}.

views/index.html

html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ .Title }}</title>
</head>
<body>
    <h1>{{ .Title }}</h1>
    <p>{{ .Content }}</p>
</body>
</html>

Restart your server and refresh your browser. Voila! The title and paragraph now show the dynamic data from your Go code. This is incredibly powerful. You can pass structs, slices, maps—any Go data structure—and render it in your template.

Let's try something a bit more complex, like a list:

go
app.Get("/tasks", func(c fiber.Ctx) error {
    return c.Render("tasks", fiber.Map{
        "Title": "My To-Do List",
        "Tasks": []string{"Buy milk", "Learn Fiber", "Build something awesome"},
    })
})

views/tasks.html

html
<!DOCTYPE html>
<html>
<head>
    <title>{{ .Title }}</title>
</head>
<body>
    <h1>{{ .Title }}</h1>
    <ul>
        {{ range .Tasks }}
            <li>{{ . }}</li>
        {{ end }}
    </ul>
</body>
</html>

Here, we used the range action to loop over our Tasks slice. The dot (.) inside the loop refers to the current item in the iteration.


4. Using Layouts and Partial Templates

As your application grows, you'll notice a lot of repeated HTML—headers, footers, navigation bars, etc. Copy-pasting this into every template is a recipe for disaster. 😱

The Problem: How can we reuse common parts of our UI across multiple pages without duplicating code?

The Solution: Layouts and partials. A layout is a "base" template that defines the overall structure of a page. Partials are smaller, reusable snippets of HTML (like a header or footer).

Let's create a layout.

views/layouts/main.html

html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Awesome Site</title>
    <style>
        body { font-family: sans-serif; }
        .container { max-width: 800px; margin: auto; padding: 20px; }
        footer { margin-top: 40px; text-align: center; color: #888; }
    </style>
</head>
<body>
    <div class="container">
        <!-- This is where the content of our other templates will be injected -->
        {{embed}}
    </div>
    <footer>
        <p>&copy; 2026 Awesome Inc.</p>
    </footer>
</body>
</html>

The {{embed}} keyword is the crucial part. It's a placeholder where the content of your specific page template will be embedded.

Now, let's create a simple "about" page template.

views/about.html

html
<h1>About Us</h1>
<p>We are a team of gophers who love building fast web apps with Fiber!</p>

To render the about.html template inside our main.html layout, we pass the layout's name as a third argument to c.Render().

go
// ...

app.Get("/about", func(c fiber.Ctx) error {
    // Render the "about" template within the "layouts/main" layout
    return c.Render("about", nil, "layouts/main")
})

// ...

Run this, and navigate to /about. You'll see the "About Us" content neatly tucked inside the main layout, complete with the footer. This is a game-changer for keeping your templates DRY (Don't Repeat Yourself).

You can also use the template action to include partials.

views/partials/header.html

html
<header>
    <a href="/">Home</a> | <a href="/about">About</a>
</header>
<hr>

Update your layout to include this partial:

views/layouts/main.html

html
<!-- ... inside the <body> tag ... -->
<div class="container">
    {{template "partials/header"}}
    {{embed}}
</div>
<!-- ... -->

Now every page using this layout will automatically have the header. This makes managing your UI components much more organized and efficient.


📚 Further Reading & References

Challenge

Your task is to build a multi-page Go web application using the Fiber framework. The application must render HTML templates for two routes: a home page (/) and an about page (/about).

Requirements:

  1. Configure a Template Engine: Initialize the standard Go html/template engine for Fiber, pointing to a views directory.
  2. Create a Main Layout: Design a layout file named main.html inside a views/layouts directory. This layout should contain the basic HTML structure (<!DOCTYPE html>, <html>, <head>, <body>), include a header partial, and have a placeholder for page-specific content.
  3. Create a Header Partial: Create a reusable header file named header.html inside a views/partials directory. This header should contain a simple navigation menu with links to the Home (/) and About (/about) pages.
  4. Create Page Templates:
    • Home Page (views/index.html): This page should display a title passed from the Go handler and a list of strings.
    • About Page (views/about.html): This page should display a title and a static paragraph of text.
  5. Implement Route Handlers:
    • The handler for / should render index.html using the main layout. It must pass a title "Welcome Home" and a slice of strings ["Feature 1", "Feature 2", "Feature 3"] to the template.
    • The handler for /about should render about.html using the main layout. It must pass a title "About Our Company" to the template.

All necessary code, including Go logic and HTML templates, must be written in the single editor window provided. Use comments to delineate the different files as shown in the initial code.

Expected result

Your final submission should be a single block of code containing both the Go application logic and the HTML templates, separated by comments.

main.go

  • An html.New instance is created, pointing to the ./views directory with a .html extension.
  • A Fiber app is initialized with the created engine via fiber.Config{Views: engine}.
  • A GET handler for / is defined. It calls c.Render("index", fiber.Map{...}, "layouts/main"). The map should contain a Title and an Items slice.
  • A GET handler for /about is defined. It calls c.Render("about", fiber.Map{...}, "layouts/main"). The map should contain a Title.

views/layouts/main.html

  • Contains the full HTML document structure (<html>, <head>, <body>).
  • The <head> section should render the page title using {{ .Title }}.
  • The <body> section should include the header partial using {{template "partials/header"}}.
  • The <body> section must also contain {{embed}} to render the page-specific content.

views/partials/header.html

  • Contains navigation HTML, such as a <nav> element with <a> tags pointing to / and /about.

views/index.html

  • Uses <h1>{{ .Title }}</h1> to display the page title.
  • Uses {{range .Items}} to iterate over the slice and render each item in a list (e.g., within <ul> and <li> tags).

views/about.html

  • Uses <h1>{{ .Title }}</h1> to display the page title.
  • Contains a static <p> tag with some placeholder text about the company.
go

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.