template

package
v3.12.0 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2024 License: MIT Imports: 40 Imported by: 4

Documentation

Index

Examples

Constants

View Source
const (
	EnvAcceptNoValue    = "GOTEMPLATE_NO_VALUE"
	EnvStrictErrorCheck = "GOTEMPLATE_STRICT_ERROR"
	EnvSubstitutes      = "GOTEMPLATE_SUBSTITUTES"
	EnvIgnoreRazor      = "GOTEMPLATE_IGNORE_RAZOR"
	EnvDebug            = "GOTEMPLATE_DEBUG"
	EnvExtensionPath    = "GOTEMPLATE_PATH"
	EnvInternalLogLevel = "GOTEMPLATE_INTERNAL_LOG_LEVEL"
	EnvLogLevel         = "GOTEMPLATE_TEMPLATE_LOG_LEVEL"
)

Environment variables that could be defined to override default behaviors. EnvAcceptNoValue is an environment variable that, when set, allows the template processor to accept variables with no value without throwing an error.

Variables

View Source
var (
	// TemplateLog is the logger used to log message during template processing
	TemplateLog = multilogger.New("gotemplate")
	// InternalLog is application logger used to follow the behaviour of the application
	InternalLog = multilogger.New("gotemplate-internal")
)
View Source
var (
	// ExtensionDepth the depth level of search of gotemplate extension from the current directory (default = 2).
	ExtensionDepth = 2

	Print      = multicolor.Print
	Printf     = multicolor.Printf
	Println    = multicolor.Println
	ErrPrintf  = multicolor.ErrorPrintf
	ErrPrintln = multicolor.ErrorPrintln
	ErrPrint   = multicolor.ErrorPrint
)

Common variables

View Source
var StrictAssignationMode = AssignationValidationWarning

StrictAssignationMode defines the global assignation validation mode.

Functions

func IsCode

func IsCode(code string) bool

IsCode determines if the supplied code appears to have gotemplate code (using default delimiters).

func IsRazor

func IsRazor(code string) bool

IsRazor determines if the supplied code appears to have Razor code (using default delimiters).

Types

type AssignationValidationType added in v3.3.5

type AssignationValidationType uint8

AssignationValidationType is the enum type to define valid global variables validation mode.

const (
	AssignationValidationDisabled AssignationValidationType = iota
	AssignationValidationWarning
	AssignationValidationStrict
)

Valid values for AssignationValidationType

type CustomHandler

type CustomHandler func(name, original string, result *string, changed bool, status error) (bool, error)

CustomHandler allows caller to supply a custom handler during the evaluation of multiple template files

type Example added in v3.3.1

type Example struct {
	Razor    string
	Template string
	Result   string
}

Example can be added to a function to describe how to use it.

func (Example) String added in v3.3.2

func (e Example) String() (result string)

type FuncCategory

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

FuncCategory represents a group of functions of the same group.

func (FuncCategory) Functions

func (fc FuncCategory) Functions() []string

Functions returns the list of functions associated with the category.

func (FuncCategory) Name

func (fc FuncCategory) Name() string

Name returns the name related to the entry.

type FuncInfo

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

FuncInfo contains the information related to a function made available to go template.

func (FuncInfo) Aliases

func (fi FuncInfo) Aliases() []string

Aliases returns the aliases related to the entry.

func (FuncInfo) Arguments

func (fi FuncInfo) Arguments() string

Arguments returns the list of arguments that must be supplied to the function.

func (FuncInfo) Description

func (fi FuncInfo) Description() string

Description returns the description related to the entry.

func (FuncInfo) Examples added in v3.3.1

func (fi FuncInfo) Examples() []Example

Examples returns the list of examples associated to the function.

func (FuncInfo) Group

func (fi FuncInfo) Group() string

Group returns the group name associated to the entry.

func (FuncInfo) IsAlias

func (fi FuncInfo) IsAlias() bool

IsAlias indicates if the current function is an alias.

func (FuncInfo) Name

func (fi FuncInfo) Name() string

Name returns the name related to the entry.

func (FuncInfo) RealName added in v3.3.2

func (fi FuncInfo) RealName() string

RealName returns the real name of a function wether it's an alias or not.

func (FuncInfo) Result

func (fi FuncInfo) Result() string

Result returns the list of output produced by the function.

func (FuncInfo) Signature

func (fi FuncInfo) Signature() string

Signature returns the function signature.

func (FuncInfo) String

func (fi FuncInfo) String() (result string)

String returns the presentation of the FuncInfo entry.

type FuncOptions

type FuncOptions map[FuncOptionsSet]interface{}

FuncOptions is a map of FuncOptionsSet that is used to associates help, aliases, arguments and groups to functions added to go template.

type FuncOptionsSet

type FuncOptionsSet int8

FuncOptionsSet defines categories that could be used to define elaborated help context when adding functions to go template.

const (
	// FuncHelp is used to associate help to functions added to go templates.
	FuncHelp FuncOptionsSet = iota
	// FuncArgs is used to associate arguments name to functions added to go templates.
	FuncArgs
	// FuncAliases is used to associate aliases to functions added to go templates.
	FuncAliases
	// FuncGroup is used to associate a group to functions added to go templates.
	FuncGroup
	// FuncExamples is used to associate examples (from razor to template to result) to functions added to go templates.
	FuncExamples
)

type Options

type Options int

Options defines the type that hold the various options & libraries that should be included

const (
	Razor Options = iota
	Extension
	Math
	Sprig
	Data
	Logging
	Runtime
	Utils
	Net
	OS
	Git
	OptionOnByDefaultCount // Trigger of options that are on by default
	Overwrite
	OutputStdout
	RenderingDisabled
	AcceptNoValue
	StrictErrorCheck
)

Options values

func (Options) String

func (i Options) String() string

type OptionsSet

type OptionsSet map[Options]bool

OptionsSet represents the map of enabled options

func DefaultOptions

func DefaultOptions() OptionsSet

DefaultOptions returns a OptionsSet with the first options turned on by default

func (OptionsSet) Set added in v3.3.11

func (os OptionsSet) Set(options ...Options) OptionsSet

Set options to true

func (OptionsSet) Unset added in v3.3.11

func (os OptionsSet) Unset(options ...Options) OptionsSet

Unset options

type String

type String = collections.String

String is an alias to collections.String

type Template

type Template struct {
	*template.Template
	// contains filtered or unexported fields
}

Template let us extend the functionalities of base go template library.

func MustNewTemplate

func MustNewTemplate(folder string, context interface{}, delimiters string, options OptionsSet, substitutes ...string) *Template

MustNewTemplate creates an Template object with default initialization. It panics if an error occurs.

func NewTemplate

func NewTemplate(folder string, context interface{}, delimiters string, options OptionsSet, substitutes ...string) (result *Template, err error)

NewTemplate creates a new Template instance with the provided parameters. It initializes the template with default or provided options, context, and substitutes.

Parameters:

  • folder: The folder path where the template is located.
  • context: The context data to be used within the template.
  • delimiters: Custom delimiters for the template, separated by commas.
  • options: A set of options to configure the template behavior.
  • substitutes: Optional additional substitution patterns.

Returns:

  • result: A pointer to the created Template instance.
  • err: An error if the template creation fails.

The function handles panics by recovering and returning an error. It sets up default options, context, and substitutes if not provided. It also processes environment variables for substitutes (GOTEMPLATE_SUBSTITUTES) and ignore razor expressions (GOTEMPLATE_IGNORE_RAZOR). GOTEMPLATE_IGNORE_RAZOR can be a json, yaml or hcl array of strings or a string with comma, newline or space separated values. GOTEMPLATE_SUBSTITUTES must be a list of substitute pattern separated by newlines.

Custom delimiters can be specified, with a maximum of three comma-separated parts.

func (*Template) Add added in v3.3.5

func (t *Template) Add(key string, value interface{})

Add allows adding a value to the template context. The context must be a dictionary to use that function, otherwise, it will panic.

func (*Template) AddFunctions

func (t *Template) AddFunctions(funcs dictionary, group string, options FuncOptions) *Template

AddFunctions add functions to the template, but keep a detailed definition of the function added for helping purpose

func (*Template) AppendIgnoreRazorExpression added in v3.9.2

func (t *Template) AppendIgnoreRazorExpression(expr ...string)

AppendIgnoreRazorExpression appends one or more Razor expressions to the list of ignored Razor expressions. This allows the template to bypass processing for the specified expressions.

Parameters:

expr: A variadic parameter representing one or more Razor expressions to be ignored.
Example
code := "Hello, @Name! From @Author"

context := map[string]string{
	"Name":   "There",
	"Author": "Obi-Wan Kenobi",
}

template := MustNewTemplate(".", context, "", nil)
template.IgnoreRazorExpression("Name")
template.AppendIgnoreRazorExpression("Author")
result, err := template.ProcessContent(code, "Internal example")
if err != nil {
	log.Fatalf("execution failed: %s", err)
}
fmt.Println("Ignored expressions:", template.GetIgnoredRazorExpressions())
fmt.Println(result)

// This reset the list of ignored expressions
template.IgnoreRazorExpression()
result, err = template.ProcessContent(code, "Internal example")
if err != nil {
	log.Fatalf("execution failed: %s", err)
}
fmt.Println("Ignored expressions:", template.GetIgnoredRazorExpressions())
fmt.Println(result)
Output:
Ignored expressions: [Author Name]
Hello, @Name! From @Author
Ignored expressions: []
Hello, There! From Obi-Wan Kenobi

func (*Template) Context added in v3.3.5

func (t *Template) Context() (result collections.IDictionary)

Context returns the context of the Template as a collections.IDictionary. It provides access to the underlying data structure that holds the template's context.

func (*Template) GetIgnoredRazorExpressions added in v3.9.2

func (t *Template) GetIgnoredRazorExpressions() []string

GetIgnoredRazorExpressions returns a slice of strings containing the ignored Razor expressions. These expressions are not processed by the template engine.

func (*Template) GetNewContext

func (t *Template) GetNewContext(folder string, useCache bool) *Template

GetNewContext returns a distinct context for each folder.

func (*Template) IgnoreRazorExpression added in v3.9.0

func (t *Template) IgnoreRazorExpression(expr ...string)

IgnoreRazorExpression sets the list of Razor expressions to be ignored by the template. This method accepts a variadic number of string arguments, allowing multiple expressions to be specified at once.

Parameters:

expr: A variadic list of strings representing the Razor expressions to ignore (can also be a regular expression).
Example
code := []string{
	"Hello, @Name! From @Author",
	"This @variable should not be changed.",
	"Neither than @thisOne or @thatOne",
	`And this @function("text", 1) won't be invoked while @add(2, 3) will be`,
}

context := map[string]string{
	"Name":   "There",
	"Author": "Obi-Wan Kenobi",
}
template := MustNewTemplate(".", context, "", nil)
template.IgnoreRazorExpression(
	"variable",     // Work with full variable name
	`th(is|at)One`, // or with a regular expression
	`function`,     // or with a function
)
result, err := template.ProcessContent(strings.Join(code, "\n"), "Internal example")
if err != nil {
	log.Fatalf("execution failed: %s", err)
}
fmt.Println(result)
Output:
Hello, There! From Obi-Wan Kenobi
This @variable should not be changed.
Neither than @thisOne or @thatOne
And this @function("text", 1) won't be invoked while 5 will be

func (*Template) IsCode

func (t *Template) IsCode(code string) bool

IsCode determines if the supplied code appears to have gotemplate code.

func (*Template) IsRazor

func (t *Template) IsRazor(code string) bool

IsRazor determines if the supplied code appears to have Razor code.

func (*Template) LeftDelim

func (t *Template) LeftDelim() string

LeftDelim returns the left delimiter used in the template. It retrieves the first element from the delimiters slice.

func (*Template) Merge added in v3.3.5

func (t *Template) Merge(values interface{})

Merge allows adding multiple values to the template context. The context and values must both be dictionary to use that function, otherwise, it will panic.

func (*Template) PrintFunctions

func (t *Template) PrintFunctions(all, long, groupByCategory bool, filters ...string)

PrintFunctions outputs the list of functions available.

func (*Template) PrintTemplates

func (t *Template) PrintTemplates(all, long bool)

PrintTemplates output the list of templates available.

func (*Template) ProcessContent

func (t *Template) ProcessContent(content, source string) (result string, err error)

ProcessContent loads and runs the file template.

func (*Template) ProcessTemplate

func (t *Template) ProcessTemplate(template, sourceFolder, targetFolder string) (resultFile string, err error)

ProcessTemplate loads and runs the template if it is a file, otherwise, it simply process the content.

func (*Template) ProcessTemplates

func (t *Template) ProcessTemplates(sourceFolder, targetFolder string, templates ...string) (resultFiles []string, err error)

ProcessTemplates loads and runs the file template or execute the content if it is not a file.

func (*Template) ProcessTemplatesWithHandler

func (t *Template) ProcessTemplatesWithHandler(sourceFolder, targetFolder string, handler CustomHandler, templates ...string) (resultFiles []string, err error)

ProcessTemplatesWithHandler loads and runs the file template or execute the content if it is not a file and call the custom handler between after each template.

func (*Template) RazorDelim

func (t *Template) RazorDelim() string

RazorDelim returns the third delimiter from the Template's delimiters slice. This delimiter is typically used for Razor-style templating.

func (*Template) RightDelim

func (t *Template) RightDelim() string

RightDelim returns the right delimiter used in the template. It retrieves the second element from the delimiters slice.

func (*Template) SetOption

func (t *Template) SetOption(option Options, value bool)

SetOption sets the specified option to the given boolean value in the Template's options map. Parameters:

  • option: The option to be set.
  • value: The boolean value to set for the specified option.

func (*Template) TempFolder

func (t *Template) TempFolder(folder string) *Template

TempFolder set temporary folder used by this template.

Jump to

Keyboard shortcuts

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