view

package
v11.1.0+incompatible Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 18, 2018 License: BSD-3-Clause Imports: 17 Imported by: 0

README

View

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

All of these five template engines have common features with common API, like Layout, Template Funcs, Party-specific layout, partial rendering and more.

Overview

// file: main.go
package main

import "github.com/kataras/iris"

func main() {
    app := iris.New()
    // Load all templates from the "./views" folder
    // where extension is ".html" and parse them
    // using the standard `html/template` package.
    app.RegisterView(iris.HTML("./views", ".html"))

    // 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/hello.html
        ctx.View("hello.html")
    })

    // Method:    GET
    // Resource:  http://localhost:8080/user/42
    app.Get("/user/{id:long}", func(ctx iris.Context) {
        userID, _ := ctx.Params().GetInt64("id")
        ctx.Writef("User ID: %d", userID)
    })

    // Start the server using a network address.
    app.Run(iris.Addr(":8080"))
}
<!-- file: ./views/hello.html -->
<html>
<head>
    <title>Hello Page</title>
</head>
<body>
    <h1>{{.message}}</h1>
</body>
</html>

Template functions

package main

import "github.com/kataras/iris"

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

    // - standard html  | iris.HTML(...)
    // - django         | iris.Django(...)
    // - pug(jade)      | iris.Pug(...)
    // - handlebars     | iris.Handlebars(...)
    // - amber          | iris.Amber(...)
    tmpl := iris.HTML("./templates", ".html")

    // built'n template funcs are:
    //
    // - {{ urlpath "mynamedroute" "pathParameter_ifneeded" }}
    // - {{ render "header.html" }}
    // - {{ render_r "header.html" }} // partial relative path to current page
    // - {{ 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)

    app.Get("/", hi)

    // http://localhost:8080
    app.Run(iris.Addr(":8080"))
}

func hi(ctx iris.Context) {
    // render the template file "./templates/hi.html"
    ctx.View("hi.html")
}
<!-- file: ./templates/hi.html -->
<b>{{greet "kataras"}}</b> <!-- will be rendered as: <b>Greetings kataras!</b> -->

Embedded

View engine supports bundled(https://github.com/shuLhan/go-bindata) template files too. go-bindata gives you two functions, Assset and AssetNames, these can be setted to each of the template engines using the .Binary function.

Example code:

package main

import "github.com/kataras/iris"

func main() {
    app := iris.New()
    // $ go get -u github.com/shuLhan/go-bindata/...
    // $ go-bindata ./templates/...
    // $ go build
    // $ ./embedding-templates-into-app
    // html files are not used, you can delete the folder and run the example
    app.RegisterView(iris.HTML("./templates", ".html").Binary(Asset, AssetNames))
    app.Get("/", hi)

    // http://localhost:8080
    app.Run(iris.Addr(":8080"))
}

type page struct {
    Title, Name string
}

func hi(ctx iris.Context) {
    //                      {{.Page.Title}} and {{Page.Name}}
    ctx.ViewData("Page", page{Title: "Hi Page", Name: "iris"})
    ctx.View("hi.html")
}

A real example can be found here: https://github.com/kataras/iris/tree/master/_examples/view/embedding-templates-into-app.

Reload

Enable auto-reloading of templates on each request. Useful while developers are in dev mode as they no neeed to restart their app on every template edit.

Example code:

pugEngine := iris.Pug("./templates", ".jade")
pugEngine.Reload(true) // <--- set to true to re-build the templates on each request.
app.RegisterView(pugEngine)

Examples

You can serve quicktemplate files too, simply by using the context#ResponseWriter, take a look at the iris/_examples/http_responsewriter/quicktemplate example.

Documentation

Index

Constants

View Source
const NoLayout = "iris.nolayout"

NoLayout disables the configuration's layout for a specific execution.

Variables

This section is empty.

Functions

This section is empty.

Types

type AmberEngine

type AmberEngine struct {
	// contains filtered or unexported fields
}

AmberEngine contains the amber view engine structure.

func Amber

func Amber(directory, extension string) *AmberEngine

Amber creates and returns a new amber view engine.

func (*AmberEngine) AddFunc

func (s *AmberEngine) AddFunc(funcName string, funcBody interface{})

AddFunc adds the function to the template's function map. It is legal to overwrite elements of the default actions: - url func(routeName string, args ...string) string - urlpath func(routeName string, args ...string) string - render func(fullPartialName string) (template.HTML, error).

func (*AmberEngine) Binary

func (s *AmberEngine) Binary(assetFn func(name string) ([]byte, error), namesFn func() []string) *AmberEngine

Binary optionally, use it when template files are distributed inside the app executable (.go generated files).

The assetFn and namesFn can come from the go-bindata library.

func (*AmberEngine) ExecuteWriter

func (s *AmberEngine) ExecuteWriter(w io.Writer, filename string, layout string, bindingData interface{}) error

ExecuteWriter executes a template and writes its result to the w writer. layout here is useless.

func (*AmberEngine) Ext

func (s *AmberEngine) Ext() string

Ext returns the file extension which this view engine is responsible to render.

func (*AmberEngine) Load

func (s *AmberEngine) Load() error

Load parses the templates to the engine. It's alos responsible to add the necessary global functions.

Returns an error if something bad happens, user is responsible to catch it.

func (*AmberEngine) Reload

func (s *AmberEngine) Reload(developmentMode bool) *AmberEngine

Reload if setted to true the templates are reloading on each render, use it when you're in development and you're boring of restarting the whole app when you edit a template file.

Note that if `true` is passed then only one `View -> ExecuteWriter` will be render each time, no concurrent access across clients, use it only on development status. It's good to be used side by side with the https://github.com/kataras/rizla reloader for go source files.

type DjangoEngine

type DjangoEngine struct {
	// contains filtered or unexported fields
}

DjangoEngine contains the amber view engine structure.

func Django

func Django(directory, extension string) *DjangoEngine

Django creates and returns a new amber view engine.

func (*DjangoEngine) AddFilter

func (s *DjangoEngine) AddFilter(filterName string, filterBody FilterFunction) *DjangoEngine

AddFilter registers a new filter. If there's already a filter with the same name, RegisterFilter will panic. You usually want to call this function in the filter's init() function: http://golang.org/doc/effective_go.html#init

Same as `RegisterFilter`.

func (*DjangoEngine) AddFunc

func (s *DjangoEngine) AddFunc(funcName string, funcBody interface{})

AddFunc adds the function to the template's Globals. It is legal to overwrite elements of the default actions: - url func(routeName string, args ...string) string - urlpath func(routeName string, args ...string) string - render func(fullPartialName string) (template.HTML, error).

func (*DjangoEngine) Binary

func (s *DjangoEngine) Binary(assetFn func(name string) ([]byte, error), namesFn func() []string) *DjangoEngine

Binary optionally, use it when template files are distributed inside the app executable (.go generated files).

The assetFn and namesFn can come from the go-bindata library.

func (*DjangoEngine) ExecuteWriter

func (s *DjangoEngine) ExecuteWriter(w io.Writer, filename string, layout string, bindingData interface{}) error

ExecuteWriter executes a templates and write its results to the w writer layout here is useless.

func (*DjangoEngine) Ext

func (s *DjangoEngine) Ext() string

Ext returns the file extension which this view engine is responsible to render.

func (*DjangoEngine) Load

func (s *DjangoEngine) Load() error

Load parses the templates to the engine. It's alos responsible to add the necessary global functions.

Returns an error if something bad happens, user is responsible to catch it.

func (*DjangoEngine) RegisterFilter

func (s *DjangoEngine) RegisterFilter(filterName string, filterBody FilterFunction) *DjangoEngine

RegisterFilter registers a new filter. If there's already a filter with the same name, RegisterFilter will panic. You usually want to call this function in the filter's init() function: http://golang.org/doc/effective_go.html#init

See http://www.florian-schlachter.de/post/pongo2/ for more about writing filters and tags.

func (*DjangoEngine) RegisterTag

func (s *DjangoEngine) RegisterTag(tagName string, parserFn TagParser) error

RegisterTag registers a new tag. You usually want to call this function in the tag's init() function: http://golang.org/doc/effective_go.html#init

See http://www.florian-schlachter.de/post/pongo2/ for more about writing filters and tags.

func (*DjangoEngine) Reload

func (s *DjangoEngine) Reload(developmentMode bool) *DjangoEngine

Reload if setted to true the templates are reloading on each render, use it when you're in development and you're boring of restarting the whole app when you edit a template file.

Note that if `true` is passed then only one `View -> ExecuteWriter` will be render each time, no concurrent access across clients, use it only on development status. It's good to be used side by side with the https://github.com/kataras/rizla reloader for go source files.

type Engine

type Engine interface {
	// Load should load the templates from a directory of by binary(assets/go-bindata).
	Load() error
	// ExecuteWriter should execute a template by its filename with an optional layout and bindingData.
	ExecuteWriter(w io.Writer, filename string, layout string, bindingData interface{}) error
	// Ext should return the final file extension which this view engine is responsible to render.
	Ext() string
}

Engine is the interface which all view engines should be implemented in order to be registered inside iris.

type EngineFuncer

type EngineFuncer interface {
	// AddFunc should adds a function to the template's function map.
	AddFunc(funcName string, funcBody interface{})
}

EngineFuncer is an addition of a view engine, if a view engine implements that interface then iris can add some closed-relative iris functions like {{ urlpath }} and {{ urlpath }}.

type Error

type Error pongo2.Error

Error conversion for pongo2.Error

func (*Error) GetError

func (error *Error) GetError() *pongo2.Error

GetError returns the `Error` as *pongo2.Error type. This method was added by balthild at https://github.com/kataras/iris/pull/765

type FilterFunction

type FilterFunction func(in *Value, param *Value) (out *Value, err *Error)

FilterFunction conversion for pongo2.FilterFunction

type HTMLEngine

type HTMLEngine struct {
	Templates *template.Template
	// contains filtered or unexported fields
}

HTMLEngine contains the html view engine structure.

func HTML

func HTML(directory, extension string) *HTMLEngine

HTML creates and returns a new html view engine. The html engine used like the "html/template" standard go package but with a lot of extra features.

func Pug

func Pug(directory, extension string) *HTMLEngine

Pug (or Jade) returns a new pug view engine. It shares the same exactly logic with the html view engine, it uses the same exactly configuration. It has got some features and a lot of functions which will make your life easier. Read more about the Jade Go Template: https://github.com/Joker/jade

Examples: https://github.com/kataras/iris/tree/master/_examples/view/template_pug_0 https://github.com/kataras/iris/tree/master/_examples/view/template_pug_1 https://github.com/kataras/iris/tree/master/_examples/view/template_pug_2 https://github.com/kataras/iris/tree/master/_examples/view/template_pug_3

func (*HTMLEngine) AddFunc

func (s *HTMLEngine) AddFunc(funcName string, funcBody interface{})

AddFunc adds the function to the template's function map. It is legal to overwrite elements of the default actions: - url func(routeName string, args ...string) string - urlpath func(routeName string, args ...string) string - render func(fullPartialName string) (template.HTML, error).

func (*HTMLEngine) AddLayoutFunc

func (s *HTMLEngine) AddLayoutFunc(funcName string, funcBody interface{}) *HTMLEngine

AddLayoutFunc adds the function to the template's layout-only function map. It is legal to overwrite elements of the default layout actions: - yield func() (template.HTML, error) - current func() (string, error) - partial func(partialName string) (template.HTML, error) - partial_r func(partialName string) (template.HTML, error) - render func(fullPartialName string) (template.HTML, error).

func (*HTMLEngine) Binary

func (s *HTMLEngine) Binary(assetFn func(name string) ([]byte, error), namesFn func() []string) *HTMLEngine

Binary optionally, use it when template files are distributed inside the app executable (.go generated files).

The assetFn and namesFn can come from the go-bindata library.

func (*HTMLEngine) Delims

func (s *HTMLEngine) Delims(left, right string) *HTMLEngine

Delims sets the action delimiters to the specified strings, to be used in subsequent calls to Parse, ParseFiles, or ParseGlob. Nested template definitions will inherit the settings. An empty delimiter stands for the corresponding default: {{ or }}.

func (*HTMLEngine) ExecuteWriter

func (s *HTMLEngine) ExecuteWriter(w io.Writer, name string, layout string, bindingData interface{}) error

ExecuteWriter executes a template and writes its result to the w writer.

func (*HTMLEngine) Ext

func (s *HTMLEngine) Ext() string

Ext returns the file extension which this view engine is responsible to render.

func (*HTMLEngine) Layout

func (s *HTMLEngine) Layout(layoutFile string) *HTMLEngine

Layout sets the layout template file which inside should use the {{ yield }} func to yield the main template file and optionally {{partial/partial_r/render}} to render other template files like headers and footers

The 'tmplLayoutFile' is a relative path of the templates base directory, for the template file with its extension.

Example: HTML("./templates", ".html").Layout("layouts/mainLayout.html")

// mainLayout.html is inside: "./templates/layouts/".

Note: Layout can be changed for a specific call action with the option: "layout" on the iris' context.Render function.

func (*HTMLEngine) Load

func (s *HTMLEngine) Load() error

Load parses the templates to the engine. It's also responsible to add the necessary global functions.

Returns an error if something bad happens, user is responsible to catch it.

func (*HTMLEngine) Option

func (s *HTMLEngine) Option(opt ...string) *HTMLEngine

Option sets options for the template. Options are described by strings, either a simple string or "key=value". There can be at most one equals sign in an option string. If the option string is unrecognized or otherwise invalid, Option panics.

Known options:

missingkey: Control the behavior during execution if a map is indexed with a key that is not present in the map.

"missingkey=default" or "missingkey=invalid"
	The default behavior: Do nothing and continue execution.
	If printed, the result of the index operation is the string
	"<no value>".
"missingkey=zero"
	The operation returns the zero value for the map type's element.
"missingkey=error"
	Execution stops immediately with an error.

func (*HTMLEngine) Reload

func (s *HTMLEngine) Reload(developmentMode bool) *HTMLEngine

Reload if setted to true the templates are reloading on each render, use it when you're in development and you're boring of restarting the whole app when you edit a template file.

Note that if `true` is passed then only one `View -> ExecuteWriter` will be render each time, no concurrent access across clients, use it only on development status. It's good to be used side by side with the https://github.com/kataras/rizla reloader for go source files.

type HandlebarsEngine

type HandlebarsEngine struct {
	// contains filtered or unexported fields
}

HandlebarsEngine contains the handlebars view engine structure.

func Handlebars

func Handlebars(directory, extension string) *HandlebarsEngine

Handlebars creates and returns a new handlebars view engine.

func (*HandlebarsEngine) AddFunc

func (s *HandlebarsEngine) AddFunc(funcName string, funcBody interface{})

AddFunc adds the function to the template's function map. It is legal to overwrite elements of the default actions: - url func(routeName string, args ...string) string - urlpath func(routeName string, args ...string) string - render func(fullPartialName string) (raymond.HTML, error).

func (*HandlebarsEngine) Binary

func (s *HandlebarsEngine) Binary(assetFn func(name string) ([]byte, error), namesFn func() []string) *HandlebarsEngine

Binary optionally, use it when template files are distributed inside the app executable (.go generated files).

The assetFn and namesFn can come from the go-bindata library.

func (*HandlebarsEngine) ExecuteWriter

func (s *HandlebarsEngine) ExecuteWriter(w io.Writer, filename string, layout string, bindingData interface{}) error

ExecuteWriter executes a template and writes its result to the w writer.

func (*HandlebarsEngine) Ext

func (s *HandlebarsEngine) Ext() string

Ext returns the file extension which this view engine is responsible to render.

func (*HandlebarsEngine) Layout

func (s *HandlebarsEngine) Layout(layoutFile string) *HandlebarsEngine

Layout sets the layout template file which should use the {{ yield }} func to yield the main template file and optionally {{partial/partial_r/render}} to render other template files like headers and footers.

func (*HandlebarsEngine) Load

func (s *HandlebarsEngine) Load() error

Load parses the templates to the engine. It's alos responsible to add the necessary global functions.

Returns an error if something bad happens, user is responsible to catch it.

func (*HandlebarsEngine) Reload

func (s *HandlebarsEngine) Reload(developmentMode bool) *HandlebarsEngine

Reload if setted to true the templates are reloading on each render, use it when you're in development and you're boring of restarting the whole app when you edit a template file.

Note that if `true` is passed then only one `View -> ExecuteWriter` will be render each time, no concurrent access across clients, use it only on development status. It's good to be used side by side with the https://github.com/kataras/rizla reloader for go source files.

type INodeTag

type INodeTag pongo2.INodeTag

INodeTag conversion for pongo2.InodeTag

type Parser

type Parser pongo2.Parser

Parser conversion for pongo2.Parser

func (*Parser) GetParser

func (parser *Parser) GetParser() *pongo2.Parser

GetParser returns the `Parser` as *pongo2.Parser type. This method was added by balthild at https://github.com/kataras/iris/pull/765

type TagParser

type TagParser func(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error)

TagParser the function signature of the tag's parser you will have to implement in order to create a new tag.

'doc' is providing access to the whole document while 'arguments' is providing access to the user's arguments to the tag:

{% your_tag_name some "arguments" 123 %}

start_token will be the *Token with the tag's name in it (here: your_tag_name).

Please see the Parser documentation on how to use the parser. See `RegisterTag` for more information about writing a tag as well.

type Token

type Token pongo2.Token

Token conversion for pongo2.Token

func (*Token) GetToken

func (token *Token) GetToken() *pongo2.Token

GetToken returns the `Token` as *pongo2.Token type. This method was added by balthild at https://github.com/kataras/iris/pull/765

type Value

type Value pongo2.Value

Value conversion for pongo2.Value

func AsSafeValue

func AsSafeValue(i interface{}) *Value

AsSafeValue works like AsValue, but does not apply the 'escape' filter.

func AsValue

func AsValue(i interface{}) *Value

AsValue converts any given value to a view.Value. Usually being used within own functions passed to a template through a Context or within filter functions.

func (*Value) GetValue

func (value *Value) GetValue() *pongo2.Value

GetValue returns the `Value` as *pongo2.Value type. This method was added by balthild at https://github.com/kataras/iris/pull/765

type View

type View struct {
	// contains filtered or unexported fields
}

View is responsible to load the correct templates for each of the registered view engines.

func (*View) AddFunc

func (v *View) AddFunc(funcName string, funcBody interface{})

AddFunc adds a function to all registered engines. Each template engine that supports functions has its own AddFunc too.

func (*View) ExecuteWriter

func (v *View) ExecuteWriter(w io.Writer, filename string, layout string, bindingData interface{}) error

ExecuteWriter calls the correct view Engine's ExecuteWriter func

func (*View) Find

func (v *View) Find(filename string) Engine

Find receives a filename, gets its extension and returns the view engine responsible for that file extension

func (*View) Len

func (v *View) Len() int

Len returns the length of view engines registered so far.

func (*View) Load

func (v *View) Load() error

Load compiles all the registered engines.

func (*View) Register

func (v *View) Register(e Engine)

Register registers a view engine.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL