Iris
Getting Started
  • What is Iris
  • 📌Getting started
    • Installation
    • Quick start
  • 🔌Routing
    • Middleware
    • API Versioning
  • 🗜️Compression
    • Index
  • ✈️Redirect
    • Redirect from Context
    • Rewrite Middleware
    • Multi Application Instances
  • 🖼️ View/Templates
    • Documentation
    • Benchmarks
    • ➲ Examples
  • 📁File Server
    • Introduction
    • Listing
    • In-memory Cache
    • HTTP/2 Push + Embedded + Cache and Compression
    • The PrefixDir function
    • Serve files from Context
    • ➲ Examples
  • 🌎Localization
    • Documentation
    • Sitemap
    • ➲ Examples
  • 🛡️Security
    • Basic Authentication
    • CORS
    • Sessions & Cookies
    • CSRF
    • JSON Web Tokens
    • Access Control
    • Anti-bot CAPTCHA
    • ➲ Examples
  • 🚀Responses
    • Text
    • HTML
    • Markdown
    • XML
    • YAML
    • Binary
    • JSON
    • JSONP
    • Problem
    • Protocol Buffers
    • MessagePack
    • Gzip
    • Content Negotiation
    • Stream
    • Server-Sent Events
    • HTTP/2 Push
    • Recorder
    • Outroduction
    • ➲ Examples
  • 📥Requests
    • URL Query
    • Headers
    • URL Path Parameters
    • Form
    • Text
    • XML
    • YAML
    • Binary
    • JSON
    • Validation
    • Protocol Buffers
    • MessagePack
    • Gzip
    • ➲ Examples
  • 💉Dependency Injection
    • Documentation
    • Register Dependency from Context
    • Inputs
    • Outputs
    • ➲ Examples
  • 🦏MVC
    • Quick start
    • Documentation
    • Handle Errors
    • Sessions
    • Websockets
    • gRPC
    • ➲ Examples
  • 🤓Resources
    • Examples
    • Starter Kits
    • Publications
    • Benchmarks
    • Support
  • 📘Contents
    • Host
      • Automatic Public Domain with TLS
    • Configuration
    • Routing
      • Path Parameter Types
      • Reverse Lookups
      • Handle HTTP errors
      • Subdomains
      • Wrap the Router
      • Context Methods
    • HTTP Method Override
    • HTTP Referrer
    • URL Query Parameters
    • Forms
    • Model Validation
    • Cache
    • Cookies
    • Sessions
      • Database
      • Flash Messages
    • Websockets
    • Sitemap
    • Localization
    • Testing
Powered by GitBook
On this page
  • Render
  • Pass Data
  • Embedded
  • Multitemplate
  • Through Middleware

Was this helpful?

  1. 🖼️ View/Templates

Documentation

PreviousMulti Application InstancesNextBenchmarks

Last updated 1 year ago

Was this helpful?

Iris supports 7 template engines out-of-the-box, developers can still use any external golang template engine, as Context.ResponseWriter() is an io.Writer.

All template engines share a common API i.e. Parse using embedded assets, Layouts and Party-specific layout, Template Funcs, Partial Render and more.

#
Name
Parser

1

HTML

2

Blocks

3

Django

4

Pug

5

Handlebars

6

Jet

7

Ace

.

A view engine can be registered per-Party. To register a view engine use the Application/Party.RegisterView(ViewEngine) method as shown below.

Load all templates from the "./views" folder where extension is ".html" and parse them using the standard html/template package.

// [app := iris.New...]
tmpl := iris.HTML("./views", ".html")
app.RegisterView(tmpl)

Render

To render or execute a view use the Context.View method inside the main route's handler. E.g. to load the ./views/hi.html template file:

ctx.View("hi") // or hi.html

Pass Data

To bind Go values with key-value pattern inside a view through middleware or main handler use the Context.ViewData method before the Context.View one.

Bind: {{.message}} with "Hello world!".

ctx.ViewData("message", "Hello world!")

To bind a Go model to a view you have two options:

1.

ctx.ViewData("user", User{})

// variable binding as {{.user.Name}}

2.

ctx.View("user-page.html", User{})

// root binding as {{.Name}}

To add a template function use the AddFunc method of the preferred view engine.

//       func name, input arguments, render value
tmpl.AddFunc("greet", func(s string) string {
    return "Greetings " + s + "!"
})

To reload on each request set the view engine's Reload method.

tmpl.Reload(true)

Embedded

tmpl.Binary(Asset, AssetNames)

Example Code:

Please read the comments too.

// file: main.go
package main

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

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

    // Parse all templates from the "./views" folder
    // where extension is ".html" and parse them
    // using the standard `html/template` package.
    tmpl := iris.HTML("./views", ".html")

    // Enable re-build on local template files changes.
    tmpl.Reload(true)

    // Default template funcs are:
    //
    // - {{ urlpath "myNamedRoute" "pathParameter_ifNeeded" }}
    // - {{ render "header.html" }}
    // and partial relative path to current page:
    // - {{ render_r "header.html" }} 
    // - {{ yield }}
    // - {{ current }}
    // Register a custom template func:
    tmpl.AddFunc("greet", func(s string) string {
        return "Greetings " + s + "!"
    })

    // Register the view engine to the views,
    // this will load the templates.
    app.RegisterView(tmpl)

    // Method:    GET
    // Resource:  http://localhost:8080
    app.Get("/", func(ctx iris.Context) {
        // Bind: {{.message}} with "Hello world!"
        ctx.ViewData("message", "Hello world!")
        // Render template file: ./views/hi.html
        ctx.View("hi.html")
    })

    app.Listen(":8080")
}
<!-- file: ./views/hi.html -->
<html>
<head>
    <title>Hi Page</title>
</head>
<body>
    <h1>{{.message}}</h1>
    <strong>{{greet "to you"}}</strong>
</body>
</html>

The rendered result will look like this:

<html>
<head>
    <title>Hi Page</title>
</head>
<body>
    <h1>Hello world!</h1>
    <strong>Greetings to you!</strong>
</body>
</html>

Multitemplate

Iris allows unlimited number of registered view engines per Application. Besides that, you can register a view engine per Party or through middleware too!.

// Register a view engine per group of routes.
adminGroup := app.Party("/admin")
adminGroup.RegisterView(iris.Blocks("./views/admin", ".html"))

Through Middleware

func middleware(views iris.ViewEngine) iris.Handler {
	return func(ctx iris.Context) {
		ctx.ViewEngine(views)
		ctx.Next()
	}
}

Usage

// Register a view engine on-fly for the current chain of handlers.
views := iris.Blocks("./views/on-fly", ".html")
views.Load()

app.Get("/", setViews(views), onFly)

To use embedded templates and not depend on local file system use the external tool and pass its Asset and AssetNames functions to the Binary method of the preferred view engine.

Open a browser tab at .

List of Examples
go-bindata
http://localhost:8080
html/template
kataras/blocks
flosch/pongo2
Joker/jade
aymerick/raymond
CloudyKit/jet
yosssi/ace