Template

Kocha uses standard Go template format that provided by html/template.

Organization

.
`-- app
    `-- view
        |-- layout
        |   `-- app.html.tmpl    # A layout file for HTML file type
        `-- root.html.tmpl       # HTML template file for Root controller

Basics

Template is highly related with Controller.

When Controller name is root, a template file name MUST be app/view/root.[extension].
[extension] is html.tmpl by default. (See File types)

Use html.tmpl extension in this example.

app/view/root.html.tmpl:

<h1>Welcome to Kocha</h1>

Output:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Welcome to Kocha</title>
</head>
<body>
  <h1>Welcome to Kocha</h1>
</body>
</html>

In fact, white-spaces in output are perhaps different from example above.

Layout

Kocha supports template layout and also enabled by default.
The default layout is app, it retrieves app/view/layout/app.[extension].
You can change the default layout by AppConfig.DefaultLayout in config/app.go.

Also multiple layout files are supported.
To use another layout instead of the default layout, set any layout name to c.Layout of Context.

For example, layout name set to sub, and when templates and Controller are following.

app/view/layout/sub.html.tmpl:

<html>
<head></head>
<body>
  {{yield .}}
  <p>This is the sub layout.</p>
</body>
</html>

In app/controller/root.go:

func (r *Root) GET(c *kocha.Context) error {
    c.Layout = "sub"
    return c.Render(nil)
}

app/view/root.html.tmpl is same as previous.

Output:

<html>
<head></head>
<body>
  <h1>Welcome to Kocha</h1>
  <p>This is the sub layout.</p>
</body>
</html>

File types

You can use template file for each file types.

See also Render.

Built-in functions (godoc)

Kocha provides various additional template functions such as follows.

in

Returns the boolean truth of whether the arg1 contains arg2.

For example, when arr is a slice of {"a", "b", "c"}:

{{if in arr "b"}}
arr have b.
{{endif}}

Output:

arr have b.

url

An alias for Reverse.

nl2br

Convert "\n" to <br> tags.

Example:

{{nl2br "some\ntext"}}

Output:

some<br>text

raw

Input string outputs it is. It won't be escaped.

Example:

{{raw "some<br>text"}}

Output:

some<br>text