decor

package module
v0.0.0-...-702b5b3 Latest Latest
Warning

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

Go to latest
Published: Jul 10, 2022 License: Apache-2.0 Imports: 6 Imported by: 0

README

decor

CI Status Go Report Card Package Doc Releases

decor contains a simple-to-user yet powerful template loader for Golang mainly focussed on the built-in packages text/template and html/template.

While these packages provide powerful templating facilities with great support for rendering textual content, using these packages to build a complete layout-based template solution involves a lot of boilerplate code. decor tries to fill this gap by providing just what's needed to reduce the boilerplate and enable a great developer experience.

Installation

$ go get github.com/halimath/decor

Decor requires go >= 1.16.

Usage

The core components provided by decor is the Templates struct which provides the rendering functionality of templates. When creating an instance you need to provide a Loader which is responsible for loading a named template.

decor provides a files loader for both text and html templates that includes capabilities to load layout files as well.

tpls := decor.Templates{
    Includes: []string{
        "layouts/base",
    },
    Loader: text.NewFilesLoader("%s.txt", "testtemplates"),
}

if err := tpls.ExecuteTemplate(os.Stdout, "a", "world"); err != nil {
    log.Fatal(err)
}

The above snippet configures a Templates value and effectively executes something like.

t, _ := "text/template".ParseFiles("testtemplates/a.txt", "testtemplates/layouts/base.txt")
t.Execute(os.Stdout, "world")

Note that error handling as well as template caching is omitted from the example; the two lines above only sketch what's happening.

Caching Templates

By default templates loaded are put into a cache the first time they are loaded. The Templates struct is safe to use across multiple goroutines, so loading and rendering template in parallel works out of the box. Internally, Templates uses an efficient sync.RWLock to guard access to the thread.

You can put Templates into development mode by setting its DevelMode-Field to true. This completely disables the cache and templates are loaded using the loader every time they are executed. This is great during development when changes made to templates become immediately effective.

Rendering HTTP Response

Its a common case to render a template producing HTML as part of a web server application using the net/http package. decor provides a utility function to handle this case as a one liner: Templates.SendHTML. The method accepts a http.ResponseWriter, a template name and template data and directly writes any output rendered from template to the HTTP response. The method also sets the content type to text/html as well as the content length.

When in development mode (see above), any errors generated during rendering will be send to the HTTP client for debugging. When not in development mode, errors will be logged and the response will be empty.

Development

The files in package html are generated from the corresponding files in package text. The code generation tool can be found in cmd/gen-html.

License

Copyright 2021 Alexander Metzner Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Documentation

Overview

Package decor contains a simple-to-user yet powerful template loader mainly focussed on the golang built-in templates text/template and html/template.

While these packages provide powerful templating facilities with great support for rendering textual content, using these packages to build a complete layout-based template solution involves a lot of boilerplate code. decor tries to fill this gap by providing just what's needed to reduce the boilerplate and enable a great developer experience.

Example (Layout)
package main

import (
	"log"
	"os"

	"github.com/halimath/decor"
	"github.com/halimath/decor/text"
)

func main() {
	tpls := decor.Templates{
		Includes: []string{
			"layouts/base",
		},
		Loader: text.NewFilesLoader("%s.txt", "testtemplates"),
	}

	if err := tpls.ExecuteTemplate(os.Stdout, "a", "world"); err != nil {
		log.Fatal(err)
	}

}
Output:

Hello, world!

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type FuncMap

type FuncMap map[string]interface{}

FuncMap defines a map of template functions.

type Loader

type Loader interface {
	// Loads the templates named names and returns them. If funcs is a non-nil, non-empty map the contained
	// functions must be made available to the template. Returns a non-nil error to indicate that loading
	// failed.
	Load(names []string, funcs FuncMap) (Template, error)
}

Loader defines the interface for implementations that load Template values from a source. Templates are loaded by name.

type Template

type Template interface {
	// Execute executes the template rendering content using data and
	// writing the output to wr. It returns an error in case of an error
	// or nil to indicate success.
	Execute(wr io.Writer, data interface{}) error
}

Template defines an internal abstraction for templates provided either by package text/template or html/template or a custom template rendering engine.

type Templates

type Templates struct {
	// When set to true DevelMode puts these templates into development mode, which
	// causes errors during rendering being written to the target writer as well
	// as templates being reload on every execution.
	DevelMode bool

	// Funcs contains a map of functions to be used in templates.
	// These are passed to every template loaded using the given
	// Templates.
	Funcs FuncMap

	// Loader is used to load Templates when requested.
	Loader Loader

	// Includes contains a list of template names to load with every template, such as helper templates or
	// layouts.
	Includes []string
	// contains filtered or unexported fields
}

Templates implements loading, caching and execution of named templates.

func (*Templates) ExecuteTemplate

func (t *Templates) ExecuteTemplate(w io.Writer, templateName string, data interface{}) error

ExecuteTemplate executes the template named templateName with data and writes the output to w. It returns any non-nil error returned from the loader or from Template.Execute.

func (*Templates) SendHTML

func (t *Templates) SendHTML(w http.ResponseWriter, templateName string, data interface{})

SendHTML executes the template named templateName with the given data (using Repository.ExecuteTemplate). It writes the rendered output to w after setting the responsive HTTP content headers. This method pays attention to the r's DevelMode: When activated any error produced from rendering the template will be send as the http response. When DevelopMode is false, any error will be suppressed possibly resulting in an empty response.

Directories

Path Synopsis
cmd
gen-html
Main contains a helper application to generate the html/template based implementation by copying the text/template based sources.
Main contains a helper application to generate the html/template based implementation by copying the text/template based sources.
Package text contains a layout based loader for text/template.
Package text contains a layout based loader for text/template.
Package text contains a layout based loader for text/template.
Package text contains a layout based loader for text/template.

Jump to

Keyboard shortcuts

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