gotemplate

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Feb 3, 2026 License: MIT Imports: 16 Imported by: 0

README

gotemplate provides a small Go command-line program that executes templates, using the text/template package from the Go standard library.

It is also a library that can be extended in order to add custom functions to the templates.

Goals

gotemplate is designed to facilitate producing markdown documentation for code. I created it so that I can include working code samples that can be easily tested, instead of copying them by hand to a README file.

It is not suitable for producing HTML. An HTML generator should use html/template instead of text/template, and also have more features, such as layouts (themes).

Design

Executing Go templates requires three main inputs:

A Function Map

A Function map (template.FuncMap) provides custom functions.

The gotemplate module defines the file function that reads a file. The library does not add it automatically to the templates, but the main executable does. This is provided as an example, but it is also useful for including code samples in documentation. If you want more functions, write your own.

The templates

These are the files parsed into text/template.Template. The function map should be defined before parsing the templates, because it is used during parsing.

The data model

This is the data passed to the Template.Execute(). Gotemplate uses a map[any]any data structure. The map is built by parsing yaml or json files, and by command-line arguments.

Example

This README.md file was generated by running the script:

readme.sh

#!/bin/sh

# generates README.md

gotemplate exec -o README.md -t README.tpl doc/common/*.tpl doc/*.tpl 

Using the templates:

It can also be generated by running the alternate script:

build.sh

#!/bin/sh

# generates README.md

gotemplate build -c doc/build.yaml -o .

which uses the configuration file:

doc/build.yaml

input_dir: ./
input_ext: .tpl
output_ext: .md 
templates:
- dir: common
  patterns:
  - "*.tpl"

This script could generate multiple output files, but we use just one.

main

The main executable also serves as an example about how to add custom functions to the templates:

main/gotemplate.go

package main

import (
	"fmt"

	"melato.org/command"
	"melato.org/gotemplate"
	"melato.org/gotemplate/cli"
	"melato.org/gotemplate/funcs"
)

var version string

func main() {
	var config gotemplate.Config
	funcs.AddFuncs(&config)
	cmd := cli.Command(&config)
	cmd.Command("version").NoConfig().RunFunc(func() {
		fmt.Printf("%s\n", version)
	}).Short("print version")
	command.Main(cmd)
}

commands

exec

The exec command uses command line arguments to specify everything. It:

  • parses a set of associated templates
  • builds a data model
  • executes one template and produces one output file
build

The build command uses a yaml configuration file to specify most parameters. The configuration file specifies:

  • a set of common templates
  • a map to uses as the data model
  • an input directory of templates.

Each input template is parsed after cloning the common templates. Therefore it has access to the common templates, but not to other input templates.

help

The help subcommands are meant to provide documentation for the template functions.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var TraceFuncs bool

Functions

func ListGlobals added in v0.2.0

func ListGlobals() error

func ListPropertyFormats added in v0.2.0

func ListPropertyFormats()

func ParseJson added in v0.2.0

func ParseJson(data []byte) (map[string]any, error)

func ParseUsage

func ParseUsage(data []byte, startPrefix string, usage map[string]string)

ParseFuncUsage parses function usage in the format

name1

description
...

name2

...

There may be additional indentation. This is the format used by "go doc text/template", under "Predefined global functions..."

if startPrefix is not empty, the parsing begins after the first line that begins with startPrefix, and ends at the first line that does not start with white space.

func ParseYaml added in v0.2.0

func ParseYaml(data []byte) (map[string]any, error)

A property parser that uses gopkg.in/yaml.v2

func SetParser added in v0.2.0

func SetParser(name string, parse PropertyParser)

Types

type BaseConfig added in v0.2.0

type BaseConfig struct {
	Funcs      Funcs
	Templates  []TemplateSet
	Properties map[string]any
}

func (*BaseConfig) Apply added in v0.2.0

func (t *BaseConfig) Apply(tpl *template.Template) error

func (*BaseConfig) CreateModel added in v0.2.0

func (t *BaseConfig) CreateModel() map[any]any

func (*BaseConfig) SetFunc added in v0.2.0

func (t *BaseConfig) SetFunc(name string, f any)

func (*BaseConfig) SetProperty added in v0.2.0

func (t *BaseConfig) SetProperty(name string, value any)

type Config added in v0.2.0

type Config struct {
	BaseConfig
	// contains filtered or unexported fields
}

Programmatic configuration of templates Use to add funcs to the FuncMap

func (*Config) AddUsage added in v0.2.0

func (t *Config) AddUsage(funcUsage map[string]string)

Add usage for functions

func (*Config) AddUsageTxt added in v0.2.0

func (t *Config) AddUsageTxt(usageTxt []byte)

Add usage for functions, in text format The usage is parsed when needed

func (*Config) FuncUsage added in v0.2.0

func (t *Config) FuncUsage(name string) error

func (*Config) GetUsage added in v0.2.0

func (t *Config) GetUsage() (map[string]string, error)

func (*Config) ListFuncs added in v0.2.0

func (t *Config) ListFuncs() error

type Funcs added in v0.2.0

type Funcs map[string]any

Funcs is used to create a template.FuncMap If a value is a function, it is copied as is to the FuncMap. Otherwise, it is converted to a func that returns it.

func (Funcs) CreateFuncMap added in v0.2.0

func (t Funcs) CreateFuncMap() template.FuncMap

Generate a template.FuncMap

type Options

type Options struct {
	PropertyFiles []string `name:"f" usage:"properties file"`
	Format        string   `name:"format" usage:"property file format"`
	KeyValues     []string `name:"D" usage:"key=value - set a property"`
	// if FS is not null, read files from FS, otherwise use os.ReadFile()
	// used for testing
	FS fs.FS
}

func (*Options) Apply added in v0.2.0

func (t *Options) Apply(values map[any]any) error

func (*Options) ParseKeyValue

func (t *Options) ParseKeyValue(keyValue string) ([]string, string)

ParseKeyValue - parse a string of the form <key1[.key2]...>=<value> The keys are separated by dots The first returned argument is the keys, and the second is the value If there is no "=", then the keys are nil and the value is the input string

type PropertyParser added in v0.2.0

type PropertyParser func([]byte) (map[string]any, error)

type TemplateOp

type TemplateOp struct {
	Base BaseConfig `name:"-"`

	TemplateName string `name:"t" usage:"template name or file"`
	OutputFile   string `name:"o" usage:"output file"`
	FileMode     string `name:"mode" usage:"output file mode"`
	Delims       string `name:"delims" usage:"template left,right delims, separated by ','"`

	Options
	// contains filtered or unexported fields
}

func (*TemplateOp) Configured

func (t *TemplateOp) Configured() error

func (*TemplateOp) Init

func (t *TemplateOp) Init() error

func (*TemplateOp) ListProperties added in v0.2.0

func (t *TemplateOp) ListProperties() error

func (*TemplateOp) ListTemplates

func (t *TemplateOp) ListTemplates(args ...string) error

func (*TemplateOp) Run

func (t *TemplateOp) Run(args ...string) error

type TemplateSet added in v0.2.0

type TemplateSet struct {
	FS       fs.FS
	Patterns []string
}

Directories

Path Synopsis
Package cli implement a Command Line Interface, using melato.org/command.
Package cli implement a Command Line Interface, using melato.org/command.
package funcs provides example functions that you can add to the templates
package funcs provides example functions that you can add to the templates

Jump to

Keyboard shortcuts

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