template

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 2, 2024 License: MIT Imports: 10 Imported by: 0

README

Simple Go Template Engine

Overview

This Go Template Engine library introduces dynamic templating for Go applications, enabling variable interpolation and data manipulation with filters. Drawing inspiration from the syntax of Liquid and Django, it simplifies the generation of dynamic content.

Getting Started

Installation

Ensure you have Go set up on your system. To add the Go Template Engine to your project, run:

go get github.com/kaptinlin/template

This command downloads the library and prepares it for use in your project.

Basic Usage
Parsing and Executing a Template

Create and parse a template, then execute it with a context:

package main

import (
	"fmt"
	"github.com/kaptinlin/template"
)

func main() {
    // Define your template
    source := "Hello, {{ name }}!"
    // Parse the template
    tpl, err := template.Parse(source)
    if err != nil {
        panic(err)
    }
    
    // Create a context and add variables
    context := template.NewContext()
    context.Set("name", "World")
    
    // Execute the template
    output, err := template.Execute(tpl, context)
    if err != nil {
        panic(err)
    }
    
    fmt.Println(output) // Output: Hello, World!
}
Quick Parsing and Execution with Render

Directly parse and execute a template in one step:

package main

import (
	"fmt"
	"github.com/kaptinlin/template"
)

func main() {
    // Define your template and context
    source := "Goodbye, {{ name }}!"
    context := template.NewContext()
    context.Set("name", "Mars")
    
    // Render the template
    output, err := template.Render(source, context)
    if err != nil {
        panic(err)
    }
    
    fmt.Println(output) // Output: Goodbye, Mars!
}
Ignoring Errors with MustExecute

Execute a template and ignore any errors, useful for templates guaranteed not to fail:

package main

import (
	"fmt"
	"github.com/kaptinlin/template"
)

func main() {
    // Define your template
    source := "Welcome, {{ name }}!"
    // Parse the template
    tpl, err := template.Parse(source)
    if err != nil {
        panic(err)
    }
    
    // Create a context and add variables
    context := template.NewContext()
    context.Set("name", "Universe")
    
    // MustExecute the template, ignoring errors
    output := template.MustExecute(tpl, context)
    
    fmt.Println(output) // Output: Welcome, Universe!
}

Syntax and Features

Variables

Enclose variables in {{ }} to embed dynamic content:

{{ userName }}

For extended syntax, refer to the documentation.

Filters

Use the pipe | to apply filters to variables:

Hello, {{ name|capitalize }}!

Detailed usage can be found in the documentation.

Custom Filters

Easily extend functionality by adding custom filters. For example, a filter to capitalize a string:

package main

import (
	"github.com/kaptinlin/template"
	"strings"
)

func capitalize(input interface{}, args ...string) (interface{}, error) {
	s, ok := input.(string)
	if !ok {
		return input, nil
	}
	return strings.Title(s), nil
}

func init() {
	template.RegisterFilter("capitalize", capitalize)
}

Use the custom filter like so:

{{ "john doe"|capitalize }}

Context Management

Contexts pass variables to templates. Here’s how to create and use one:

context := template.NewContext()
context.Set("key", "value")

How to Contribute

Contributions to the template package are welcome. If you'd like to contribute, please follow the contribution guidelines.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrContextKeyNotFound is returned when a key is not found in the context.
	ErrContextKeyNotFound = errors.New("key not found in context")

	// ErrContextInvalidKeyType is returned when an unexpected type is encountered while navigating the context.
	ErrContextInvalidKeyType = errors.New("invalid key type for navigation")

	// ErrContextIndexOutOfRange is returned when an index is out of range in the context.
	ErrContextIndexOutOfRange = errors.New("index out of range in context")
)
View Source
var (
	// ErrFilterInputNotSlice indicates a filter expected a slice but received a different type.
	ErrFilterInputNotSlice = errors.New("filter input is not a slice")

	// ErrFilterInputNotNumeric indicates a filter expected a numeric value but received a different type.
	ErrFilterInputNotNumeric = errors.New("filter input is not numeric")

	// ErrFilterInputInvalidTimeFormat indicates a filter expected a valid time format but didn't receive it.
	ErrFilterInputInvalidTimeFormat = errors.New("filter input has an invalid time format")

	// ErrFilterInputUnsupportedType indicates the filter received a type it does not support.
	ErrFilterInputUnsupportedType = errors.New("filter input is of an unsupported type")
)
View Source
var ErrFilterArgsInvalid = errors.New("filter arguments are invalid")

ErrFilterArgsInvalid indicates an issue with the filter arguments, such as wrong type, format, or number of arguments.

View Source
var ErrFilterInputEmpty = errors.New("filter input is empty")

ErrFilterInputEmpty indicates that the input value is empty or nil.

View Source
var ErrFilterInputInvalid = errors.New("filter input is invalid")

ErrFilterInputInvalid indicates an issue with the filter input value being of an unexpected type or format.

View Source
var ErrFilterNotFound = errors.New("filter not found")

ErrFilterNotFound indicates that the requested filter was not found in the global registry.

View Source
var ErrInsufficientArgs = errors.New("insufficient arguments provided")

ErrInsufficientArgs indicates that the filter was called with insufficient arguments.

Functions

func ApplyFilters

func ApplyFilters(value interface{}, fs []Filter, ctx Context) (interface{}, error)

ApplyFilters executes a series of filters on a value within a context, supporting variable arguments.

func Execute

func Execute(tpl *Template, ctx Context) (string, error)

Execute renders the template with provided context.

func MustExecute

func MustExecute(tpl *Template, ctx Context) string

MustExecute renders the template with provided context, ignoring errors.

func RegisterFilter

func RegisterFilter(name string, fn FilterFunc) error

RegisterFilter adds a filter to the global registry with name validation.

func Render

func Render(source string, ctx Context) (string, error)

Render combines parsing and executing a template with the given context for convenience.

Types

type Context

type Context map[string]interface{}

Context stores template variables.

func NewContext

func NewContext() Context

NewContext creates a Context instance.

func (Context) Get

func (c Context) Get(key string) (interface{}, error)

Get retrieves a variable's value from the Context, supporting nested keys.

func (Context) Set

func (c Context) Set(key string, value interface{})

Set inserts a variable into the Context, supporting nested keys.

type Filter

type Filter struct {
	Name string
	Args []FilterArg
}

Filter defines a transformation to apply to a template variable.

type FilterArg

type FilterArg interface {
	Value() interface{}
	Type() string
}

FilterArg represents the interface for filter arguments.

type FilterFunc

type FilterFunc func(interface{}, ...string) (interface{}, error)

FilterFunc represents the signature of functions that can be applied as filters.

type Node

type Node struct {
	Type     string
	Text     string
	Variable string
	Filters  []Filter
	Children []*Node
}

Node defines a single element within a template, such as text, variable, or control structure.

type NumberArg

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

NumberArg holds a number argument.

func (NumberArg) Type

func (a NumberArg) Type() string

func (NumberArg) Value

func (a NumberArg) Value() interface{}

type Parser

type Parser struct{}

Parser analyzes template syntax.

func NewParser

func NewParser() *Parser

NewParser creates a Parser with a compiled regular expression for efficiency.

func (*Parser) Parse

func (p *Parser) Parse(src string) (*Template, error)

Parse transforms a template string into a Template.

type StringArg

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

StringArg holds a string argument.

func (StringArg) Type

func (a StringArg) Type() string

func (StringArg) Value

func (a StringArg) Value() interface{}

type Template

type Template struct {
	Nodes []*Node
}

Template represents a structured template that can be executed with a given context.

func NewTemplate

func NewTemplate() *Template

NewTemplate creates an empty template, ready to be populated with nodes.

func Parse

func Parse(source string) (*Template, error)

Parse parses a template string and returns a Template instance.

func (*Template) Execute

func (t *Template) Execute(ctx Context) (string, error)

Execute combines template data with the provided context to produce a string.

func (*Template) MustExecute

func (t *Template) MustExecute(ctx Context) string

MustExecute combines template data with the provided context to produce a string, ignoring errors.

type VariableArg

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

VariableArg holds a variable argument.

func (VariableArg) Type

func (a VariableArg) Type() string

func (VariableArg) Value

func (a VariableArg) Value() interface{}

Directories

Path Synopsis
examples
context command
filters command
hello_world command
object command

Jump to

Keyboard shortcuts

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