Skip to content

View/Templates

Iris provides a powerful templating system with support for multiple template engines.

Basic Usage

go
package main

import "github.com/kataras/iris/v12"

func main() {
    app := iris.New()

    // Register the view engine
    app.RegisterView(iris.HTML("./views", ".html"))

    app.Get("/", func(ctx iris.Context) {
        // Render template with data
        ctx.View("index.html", iris.Map{
            "title": "Hello World",
            "message": "Welcome to Iris!",
        })
    })

    app.Listen(":8080")
}

Template Engines

HTML Templates

go
// Register HTML templates
tmpl := iris.HTML("./views", ".html")
tmpl.Layout("layouts/main.html")
tmpl.Reload(true) // Enable reloading for development
app.RegisterView(tmpl)

// Use in handler
app.Get("/", func(ctx iris.Context) {
    ctx.ViewData("title", "Home Page")
    ctx.View("home.html")
})

Django Templates

go
import "github.com/kataras/iris/v12/view/django"

// Register Django templates
tmpl := django.New("./views", ".html")
tmpl.Reload(true)
app.RegisterView(tmpl)

Pug Templates

go
import "github.com/kataras/iris/v12/view/pug"

// Register Pug templates
tmpl := pug.New("./views", ".pug")
tmpl.Reload(true)
app.RegisterView(tmpl)

Layouts

go
// Set default layout
tmpl := iris.HTML("./views", ".html")
tmpl.Layout("layouts/main.html")
app.RegisterView(tmpl)

// Override layout for specific route
app.Get("/custom", func(ctx iris.Context) {
    ctx.ViewLayout("layouts/custom.html")
    ctx.View("page.html")
})

// Disable layout for specific route
app.Get("/no-layout", func(ctx iris.Context) {
    ctx.ViewLayout(nil)
    ctx.View("page.html")
})

Template Functions

go
tmpl := iris.HTML("./views", ".html")

// Add custom template function
tmpl.AddFunc("greet", func(name string) string {
    return "Hello " + name + "!"
})

app.RegisterView(tmpl)

// Use in template
// {{ greet "John" }}

Partial Templates

go
// Register partial
tmpl := iris.HTML("./views", ".html")
tmpl.AddFunc("partial", tmpl.Partial)
app.RegisterView(tmpl)

// Use in template
// {{ partial "header.html" . }}

Error Handling

go
app.Get("/", func(ctx iris.Context) {
    err := ctx.View("page.html", data)
    if err != nil {
        ctx.StatusCode(iris.StatusInternalServerError)
        ctx.WriteString("Template Error")
        return
    }
})

Caching

go
tmpl := iris.HTML("./views", ".html")

// Enable template caching
tmpl.Reload(false) // Disable reloading
app.RegisterView(tmpl)

Built with excellence by Hellenic Development, delivering enterprise-grade solutions.