Prerequisites
- Go 1.22 or later installed
- Basic understanding of Go and HTML
- A text editor
Step 1: Create Your Project
First, create a new directory and initialize a Go module:Step 2: Create the Directory Structure
The view package expects templates in a specific structure:Step 3: Create the Layout
A layout is the HTML shell that wraps your pages. Createviews/layouts/default.html:
{{.Data.Title}}- Accesses the “Title” field from data you pass{{.Content}}- This is where the page content gets inserted- The layout provides the common structure (doctype, head, nav, footer)
Step 4: Create Pages
Pages are templates that provide the main content. Createviews/pages/home.html:
{{.Data.Name}}- Accesses data passed from your handler{{range .Data.Features}}...{{end}}- Loops through a list{{.}}- Inside range, this is the current item- Page content is automatically inserted into the layout’s
{{.Content}}
views/pages/about.html:
Step 5: Create the Go Application
Now createmain.go:
- Create engine -
view.New()creates a view engine with your configuration - Add middleware -
app.Use(engine.Middleware())stores the engine in every request context - Render pages -
view.Render(c, "home", data)renders the “home” page with data
Step 6: Run Your Application
Start the server:http://localhost:8080. You should see:
- The home page with your name and features list
- A styled button
- Navigation to the About page
views/pages/home.html and refreshing your browser - the changes appear instantly because Development mode is enabled!
Understanding the Data Flow
Here’s what happens when someone visits your site:Understanding Template Data
Templates receive a wrapper structure, not just your data directly:Common Patterns
Using a Different Layout
Override the default layout for specific pages:views/layouts/admin.html instead of default.html.
Rendering Without a Layout
For partial HTML responses (AJAX, htmx, etc.):Using the Engine Directly
If you need the engine instance:Next Steps
You’ve learned the basics! Here’s what to explore next:- Engine - All configuration options explained
- Templates - Deep dive into Go template syntax
- Layouts - Advanced layout patterns
- Functions - Built-in and custom template functions
- Production - Embedding templates and caching for production
Troubleshooting
”template not found” Error
Check that:- Your
viewsdirectory exists withlayouts/andpages/subdirectories - The file extension matches your Config (default is
.html) - The name in
Render()matches the filename inpages/(without extension)
Changes Not Appearing
Make sureDevelopment: true is set in your view config. In production mode (the default), templates are cached.
”layout not found” Error
Make sure the layout file exists atviews/layouts/default.html (or your custom DefaultLayout value).