blocks

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2020 License: MIT Imports: 13 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:

  • Embedded templates through go-bindata
  • Load with optional context for cancelation
  • Reload templates on development stage
  • Full Layouts and Blocks support
  • Markdown Content
  • Global FuncMap

Installation

The only requirement is the Go Programming Language.

$ go get github.com/kataras/blocks

Getting Started

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")

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()

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

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
	}
}

To parse files that are translated as Go code, inside the executable program itself, pass the go-bindata's generated Asset and AssetNames functions to the Assets method:

views := blocks.New("./views").Assets(Asset, AssetNames)

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 AssetFunc

type AssetFunc func(string) ([]byte, error) // key = full pathname, value = a func which should return its contents.

AssetFunc type declaration for reading content based on a name.

type AssetNamesFunc

type AssetNamesFunc func() []string

AssetNamesFunc type declaration for returning all filenames (no dirs).

type Blocks

type Blocks struct {

	// Root and Templates can be used after `Load`.
	Root      *template.Template
	Templates 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(rootDir string) *Blocks

New returns a fresh Blocks engine instance. It loads the templates based on the given "rootDir". By default the layout files should be located at "$rootDir/layouts" sub-directory, 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.

Use the `Assets` method to define custom Asset and AssetNames functions (e.g. generated go-bindata contents).

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.

func (*Blocks) Assets

func (v *Blocks) Assets(asset AssetFunc, names AssetNamesFunc) *Blocks

Assets sets the function which reads contents based on a filename and a function that returns all the filenames. These functions are used to parse the corresponding files into templates. You do not need to set them when the given "rootDir" was a system directory. It's mostly useful when the application contains embedded template files, e.g. pass go-bindata's `Asset` and `AssetNames` functions to load templates from go-bindata generated content.

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 root "dir" 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.

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. Parse templates on each request.

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
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