blocks

package module
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2023 License: MIT Imports: 14 Imported by: 11

README

Blocks

build status report card godocs

Blocks is a, simple, Go-idiomatic view engine based on html/template, plus the following features:

Installation

The only requirement is the Go Programming Language.

$ go get github.com/kataras/blocks

Getting Started

Create a folder named ./views and put some HTML template files.

│   main.go
└───views
    |   index.html
    ├───layouts
    │       main.html
    ├───partials
    │       footer.html

Now, open the ./views/layouts/main.html file and paste the following:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ if .Title }}{{ .Title }}{{ else }}Default Main Title{{ end }}</title>
</head>
<body>
    {{ template "content" . }}

<footer>{{ partial "partials/footer" .}}</footer>
</body>
</html>

The template "content" . is a Blocks builtin template function which renders the main content of your page that should be rendered under this layout. The block name should always be "content".

The partial is a Blocks builtin template function which renders a template inside other template.

The . (dot) passes the template's root binding data to the included templates.

Continue by creating the ./views/index.html file, copy-paste the following markup:

<h1>Index Body</h1>

In order to render index on the main layout, create the ./main.go file by following the below.

Import the package:

import "github.com/kataras/blocks"

The blocks package is fully compatible with the standard library. Use the New(directory string) function to return a fresh Blcoks view engine that renders templates.

This directory can be used to locate system template files or to select the wanted template files across a range of embedded data (or empty if templates are not prefixed with a root directory).

views := blocks.New("./views")

The default layouts directory is $dir/layouts, you can change it by blocks.New(...).LayoutDir("otherLayouts").

To parse files that are translated as Go code, inside the executable program itself, pass the go-bindata's generated latest version's AssetFile method to the New function:

$ go get -u github.com/go-bindata/go-bindata
views := blocks.New(AssetFile())

After the initialization and engine's customizations the user SHOULD call its Load() error or LoadWithContext(context.Context) error method once in order to parse the files into templates.

err := views.Load()

To render a template through a compatible io.Writer use the ExecuteTemplate(w io.Writer, tmplName, layoutName string, data interface{}) method.

func handler(w http.ResponseWriter, r *http.Request) {
	data := map[string]interface{}{
		"Title": "Index Title",
	}

	err := views.ExecuteTemplate(w, "index", "main", data)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}

There are several methods to customize the engine, before Load, including Delims, Option, Funcs, Extension, RootDir, LayoutDir, LayoutFuncs, DefaultLayout and Extensions. You can learn more about those in our godocs.

Please navigate through _examples directory for more.

License

This software is licensed under the MIT License.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Register

func Register(funcMap template.FuncMap)

Register register a function map that will be available across all Blocks view engines. The values (functions) should be compatible with a standard html/template function, however as a special feature, the function input's can be a type of func(*Blocks) (fn interface{}) or func(*Blocks) template.FuncMap as well, so it can use the current engine's methods such as `ParseTemplate`. It's legal to override previous functions.

It is used like the `database/sql.Register` function.

Usage:

	package myFuncsCollection1
	func init() {
	  blocks.Register(a_funcMap)
	}

	package myFuncsCollection2
	func init() {
	  blocks.Register(anothrer_funcMap)
	}

	package main
	import _ "myFuncsCollection1"
	import _ "myFuncsCollection2"

	func main() {
	  views := blocks.New("./views")
	}
 Views contains the functions of both collections.

func Set

func Set(v *Blocks) func(http.Handler) http.Handler

Set returns a handler wrapper which sets the current view engine to this "v" Blocks. Useful when the caller needs multiple Blocks engine instances per group of routes. Note that this is entirely optional, the caller could just wrap a function of func(v *Blocks) and return a handler which will directly use it. See `Get` too.

Types

type Blocks

type Blocks struct {

	// Root, Templates and Layouts can be accessed after `Load`.
	Root *template.Template

	Templates, Layouts map[string]*template.Template
	// contains filtered or unexported fields
}

Blocks is the main structure which holds the necessary information and options to parse and render templates. See `New` to initialize a new one.

func Get

func Get(r *http.Request) *Blocks

Get retrieves the associated Blocks view engine retrieved from the request's context. See `Set` too.

func New

func New(fs interface{}) *Blocks

New returns a fresh Blocks engine instance. It loads the templates based on the given fs FileSystem (or string). By default the layout files should be located at "$rootDir/layouts" sub-directory (see `RootDir` method), change this behavior can be achieved through `LayoutDir` method before `Load/LoadContext`. To set a default layout name for an empty layout definition on `ExecuteTemplate/ParseTemplate` use the `DefaultLayout` method.

The user can customize various options through the Blocks methods. The user of this engine MUST call its `Load/LoadWithContext` method once before any call of `ExecuteTemplate` and `ParseTemplate`.

Global functions registered through `Register` package-level function will be inherited from this engine. To add a function map to this engine use its `Funcs` method.

The default extension can be changed through the `Extension` method. More extension parsers can be added through the `Extensions` method. The left and right delimeters can be customized through its `Delims` method. To reload templates on each request (useful for development stage) call its `Reload(true)` method.

Usage: New("./views") or New(http.Dir("./views")) or New(embeddedFS) or New(AssetFile()) for embedded data.

func (*Blocks) DefaultLayout

func (v *Blocks) DefaultLayout(layoutName string) *Blocks

DefaultLayout sets the "layoutName" to be used when the `ExecuteTemplate`'s one is empty.

func (*Blocks) Delims

func (v *Blocks) Delims(left, right string) *Blocks

Delims sets the action delimiters to the specified strings, to be used in Load. Nested template definitions will inherit the settings. An empty delimiter stands for the corresponding default: {{ or }}. The return value is the engine, so calls can be chained.

func (*Blocks) ExecuteTemplate

func (v *Blocks) ExecuteTemplate(w io.Writer, tmplName, layoutName string, data interface{}) error

ExecuteTemplate applies the template associated with "tmplName" to the specified "data" object and writes the output to "w". If an error occurs executing the template or writing its output, execution stops, but partial results may already have been written to the output writer.

If "layoutName" and "v.defaultLayoutName" are both empty then the template is executed without a layout.

A template may be executed safely in parallel, although if parallel executions share a Writer the output may be interleaved.

func (*Blocks) Extension

func (v *Blocks) Extension(ext string) *Blocks

Extension sets the template file extension (with dot). Defaults to ".html".

func (*Blocks) Extensions

func (v *Blocks) Extensions(ext string, parser ExtensionParser) *Blocks

Extensions registers a parser that will be called right before a file's contents parsed as a template. The "ext" should start with dot (.), e.g. ".md". The "parser" is a function which accepts the original file's contents and should return the parsed ones, e.g. return markdown.Run(contents), nil.

The default underline map contains a single element of ".md": markdown.Run, which is responsible to convert markdown files to html right before its contents are given to the template's parser.

To override an extension handler pass a nil "parser".

func (*Blocks) Funcs

func (v *Blocks) Funcs(funcMap template.FuncMap) *Blocks

Funcs adds the elements of the argument map to the root template's function map. It must be called before the engine is loaded. It panics if a value in the map is not a function with appropriate return type. However, it is legal to overwrite elements of the map. The return value is the engine, so calls can be chained.

The default function map contains a single element of "partial" which can be used to render templates directly.

func (*Blocks) LayoutDir

func (v *Blocks) LayoutDir(relToDirLayoutDir string) *Blocks

LayoutDir sets a custom layouts directory, always relative to the "rootDir" one. Layouts are recognised by their prefix names. Defaults to "layouts".

func (*Blocks) LayoutFuncs

func (v *Blocks) LayoutFuncs(funcMap template.FuncMap) *Blocks

LayoutFuncs same as `Funcs` but this map's elements will be added only to the layout templates. It's legal to override elements of the root `Funcs`.

func (*Blocks) Load

func (v *Blocks) Load() error

Load parses the templates, including layouts, through the html/template standard package into the Blocks engine.

func (*Blocks) LoadWithContext

func (v *Blocks) LoadWithContext(ctx context.Context) error

LoadWithContext accepts a context that can be used for load cancelation, deadline/timeout. It parses the templates, including layouts, through the html/template standard package into the Blocks engine.

func (*Blocks) Option

func (v *Blocks) Option(opt ...string) *Blocks

Option sets options for the templates. 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 (*Blocks) ParseTemplate

func (v *Blocks) ParseTemplate(tmplName, layoutName string, data interface{}) (string, error)

ParseTemplate parses a template based on its "tmplName" name and returns the result. Note that, this does not reload the templates on each call if Reload was set to true. To refresh the templates you have to manually call the `Load` upfront.

func (*Blocks) PartialFunc

func (v *Blocks) PartialFunc(partialName string, data interface{}) (template.HTML, error)

PartialFunc returns the parsed result of the "partialName" template's "content" block.

func (*Blocks) Reload

func (v *Blocks) Reload(b bool) *Blocks

Reload will turn on the `Reload` setting, for development use. It forces the `ExecuteTemplate` to re-parse the templates on each incoming request.

func (*Blocks) RootDir added in v0.0.3

func (v *Blocks) RootDir(root string) *Blocks

RootDir sets the directory to use as the root one inside the provided File System.

type ContextKeyType

type ContextKeyType struct{}

ContextKeyType is the type which `Set` request's context value is using to store the current Blocks engine.

See `Set` and `Get`.
var ContextKey ContextKeyType

ContextKey is the request's context value for a blocks engine.

See `Set` and `Get`.

type ErrNotExist

type ErrNotExist struct {
	Name string
}

ErrNotExist reports whether a template was not found in the parsed templates tree.

func (ErrNotExist) Error

func (e ErrNotExist) Error() string

Error implements the `error` interface.

type ExtensionParser

type ExtensionParser func([]byte) ([]byte, error)

ExtensionParser type declaration to customize other extension's parsers before passed to the template's one.

Directories

Path Synopsis
_examples
embedded-bindata
Package main generated by go-bindata.// sources: ../basic/views/500.html ../basic/views/index.html ../basic/views/layouts/error.html ../basic/views/layouts/main.html ../basic/views/partials/footer.html
Package main generated by go-bindata.// sources: ../basic/views/500.html ../basic/views/index.html ../basic/views/layouts/error.html ../basic/views/layouts/main.html ../basic/views/partials/footer.html
funcs/mycollection
Package mycollection contains a template.FuncMap that should be registered across all Blocks view engines.
Package mycollection contains a template.FuncMap that should be registered across all Blocks view engines.

Jump to

Keyboard shortcuts

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