xtemplate

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Sep 15, 2025 License: MIT Imports: 19 Imported by: 0

README

xtemplate

Actions Status Coverage Status PkgGoDev go-report

A secure Go template engine with a restricted set of functions for safe template execution. xtemplate provides enhanced control over template functionality by allowing you to specify which functions are permitted, making it ideal for scenarios where you need to execute untrusted templates safely.

Features

  • 🔒 Security-focused: Restrict which functions can be used in templates
  • 🚀 Rich function library: Includes functions for strings, paths, JSON, conversions, and more
  • 🎯 Fine-grained control: Allow entire namespaces or individual functions
  • Quick execution: Simple API for common use cases
  • 🔄 Early return: Special return function to short-circuit template execution
  • ⚠️ Custom error: Special error function to stop template execution and return an error
  • 📦 Zero dependencies: Built on Go's standard library

Installation

go get github.com/Eun/xtemplate

Quick Start

Basic Usage
package main

import (
	"os"
	"text/template"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main()
	// Create a template with restricted functions
	t := template.New("example")
	t = t.Funcs(xtemplate.FuncMap(t,
		funcs.Strings,     // Allow all string functions
		funcs.URLJoinPath, // Allow only url.JoinPath function
	))

	tmpl := `{{ strings.ToLower (url.JoinPath "https://example.com" "INDEX.HTML") }}`
	t, err := t.Parse(tmpl)
	if err != nil {
		panic(err)
	}

	err = xtemplate.Execute(t, os.Stdout, nil)
	if err != nil {
		panic(err)
	}
	// Output: https://example.com/index.html
}
Quick Execute (One-liner)

For simple cases, use QuickExecute:

package main

import (
	"fmt"
	"os"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func init() {
	os.Setenv("HOME", "/root")
}

func main()
	result, err := xtemplate.QuickExecute(
		"{{ filepath.ToSlash ( filepath.Join ( os.Getenv \"HOME\" ) .file ) }}",
		map[string]any{"file": ".bashrc"},
		funcs.Safe,     // Safe functions
		funcs.OSGetenv, // Additional OS function
	)
	if err != nil {
		panic(err)
	}
	fmt.Println(result) // Output: /root/.bashrc
}

Available Function Namespaces

Namespace Description Example Functions
strings String manipulation ToLower, ToUpper, Replace, Split, Join
conv Type conversions ToString, ToInt, ToBool, ToFloat64
json JSON operations Marshal, Unmarshal, Valid
filepath File path operations Join, Dir, Base, Ext, Clean
path URL path operations Join, Dir, Base, Ext, Clean
dict Dictionary/map operations New, HasKey, HasValue, Keys
slice Slice operations New, Sort, Reverse, Contains
url URL operations JoinPath, QueryEscape
os OS operations Getenv, Hostname, UserHomeDir
tmpl Template operations Exec
regexp Regular expressions Match, ReplaceAll, Split
cmp Comparison operations Or

Function Collections

Use predefined collections for common scenarios:

import "github.com/Eun/xtemplate/funcs"

// Safe functions - recommended for untrusted templates
funcs.Safe

// All functions - use with caution
funcs.All

// Individual namespaces
funcs.Strings
funcs.Conv
funcs.JSON
// ... etc

// Individual functions
funcs.StringsToLower
funcs.URLJoinPath
funcs.OSGetenv
// ... etc

Advanced Examples

Data Processing Template
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main()
	data := map[string]any{
		"users": []map[string]any{
			{"firstname": "John", "lastname": "Doe", "age": "25", "active": "true"},
			{"firstname": "Jane", "lastname": "Smith", "age": "30", "active": "false"},
		},
	}

	tmpl := `
{{- range .users -}}
Name: {{ strings.Join ( slice.NewStrings .firstname .lastname ) " " }}
Age: {{ conv.ToInt .age }}
Active: {{ conv.ToBool .active }}
---
{{ end -}}
`

	result, err := xtemplate.QuickExecute(tmpl, data, funcs.Safe)
	if err != nil {
		panic(err)
	}
	fmt.Println(result)
	// Output: Name: John Doe
	// Age: 25
	// Active: true
	// ---
	// Name: Jane Smith
	// Age: 30
	// Active: false
	// ---
}
Early Return Example

Use the special return function to exit template execution early:

package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main()
	tmpl := `
{{- define "getName" -}}
{{- if not .lastname -}}{{- return .firstname -}}{{- end -}}
{{- if eq .lastname "" -}}{{- return .firstname -}}{{- end -}}
{{ .lastname }}, {{ .firstname }}
{{- end -}}

Users:
{{ range .users -}}
* {{ tmpl.Exec "getName" . }}
{{ end -}}
`
	data := map[string]any{
		"users": []map[string]any{
			{"firstname": "Joe", "lastname": "Doe"},
			{"firstname": "Alice"},
		},
	}
	result, err := xtemplate.QuickExecute(tmpl, data, funcs.Safe)
	if err != nil {
		panic(err)
	}
	fmt.Println(result)
	// Output: Users:
	// * Doe, Joe
	// * Alice
}
Custom Error Example

Use the special error function to exit template execution early with an error:

package main

import (
	"errors"
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main()
	tmpl := `
{{- if not .user -}}
{{ error "No user provided" }}
{{- end -}}
Welcome, {{ .user.name }}!
`

	result, err := xtemplate.QuickExecute(tmpl, map[string]any{}, funcs.Safe)
	if err != nil {
		var e xtemplate.CustomError
		if ok := errors.As(err, &e); ok {
			fmt.Println("Error:", e.Message) // Output: Error: No user provided
		} else {
			panic(err)
		}
	}
	fmt.Println(result)
}
Template Inclusion

Define and include sub-templates:

package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main()
	tmpl := `
{{- define "getName" -}}
	{{- if not .user -}}
		{{ return "Anonymous" }}
	{{- end -}}
	{{- return .user.name -}}
{{- end -}}
Welcome, {{ tmpl.Exec "getName" . }}!
`

	result, err := xtemplate.QuickExecute(tmpl, map[string]any{}, funcs.Safe)
	if err != nil {
		panic(err)
	}
	fmt.Println(result)
	// Output: Welcome, Anonymous!
}

Security Considerations

xtemplate is designed for secure template execution:

  • Use funcs.Safe for untrusted templates
  • Whitelist specific functions when you need more control
  • ⚠️ Be cautious with funcs.All - includes potentially dangerous functions
  • ⚠️ OS functions like os.Getenv can expose sensitive information
  • ⚠️ Template functions like tmpl.Execute can lead to infinite recursion
Safe vs All Functions
// Safe for untrusted templates
funcs.Safe // Includes: strings, conv, json, filepath, path, dict, slice, url, tmpl, cmp

// Use with caution - includes OS functions and more
funcs.All // Includes everything, including os.Getenv, os.Hostname, etc.

Error Handling

result, err := xtemplate.QuickExecute(template, data, funcs.Safe)
if err != nil {
    // Handle parsing or execution errors
    var funcErr *xtemplate.FuncNotAllowedError
    if errors.As(err, &funcErr) {
        fmt.Printf("Function not allowed: %s.%s\n", funcErr.Func.Namespace, funcErr.Func.Name)
    }
}

Complete Function List

See the GoDoc for a complete list of available functions and their descriptions.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

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

Documentation

Overview

Package xtemplate provides a way to create text/template with a restricted set of functions. It includes functions from various standard library packages such as path, filepath, strings, os, and encoding/json. Users can specify which functions are allowed to be used in the templates, enhancing security and control. The package also provides a special "return" function to short-circuit template execution and return a value. This is useful for scenarios where you want to exit a template early with a specific value without rendering the rest of the template.

Example
package main

import (
	"os"
	"text/template"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	// Create a template with restricted functions
	t := template.New("example")
	t = t.Funcs(xtemplate.FuncMap(t,
		funcs.Strings,     // Allow all string functions
		funcs.URLJoinPath, // Allow only url.JoinPath function
	))

	tmpl := `{{ strings.ToLower (url.JoinPath "https://example.com" "INDEX.HTML") }}`
	t, err := t.Parse(tmpl)
	if err != nil {
		panic(err)
	}

	err = xtemplate.Execute(t, os.Stdout, nil)
	if err != nil {
		panic(err)
	}
}
Output:

https://example.com/index.html
Example (Fifth)
package main

import (
	"errors"
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	tmpl := `
{{- if not .user -}}
{{ error "No user provided" }}
{{- end -}}
Welcome, {{ .user.name }}!
`

	result, err := xtemplate.QuickExecute(tmpl, map[string]any{}, funcs.Safe)
	if err != nil {
		var e xtemplate.CustomError
		if ok := errors.As(err, &e); ok {
			fmt.Println("Error:", e.Message)
		} else {
			panic(err)
		}
	}
	fmt.Println(result)
}
Output:

Error: No user provided
Example (Fourth)
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	tmpl := `
{{- define "getName" -}}
{{- if not .lastname -}}{{- return .firstname -}}{{- end -}}
{{- if eq .lastname "" -}}{{- return .firstname -}}{{- end -}}
{{ .lastname }}, {{ .firstname }}
{{- end -}}

Users:
{{ range .users -}}
* {{ tmpl.Exec "getName" . }}
{{ end -}}
`
	data := map[string]any{
		"users": []map[string]any{
			{"firstname": "Joe", "lastname": "Doe"},
			{"firstname": "Alice"},
		},
	}
	result, err := xtemplate.QuickExecute(tmpl, data, funcs.Safe)
	if err != nil {
		panic(err)
	}
	fmt.Println(result)
}
Output:

Users:
* Doe, Joe
* Alice
Example (Second)
package main

import (
	"fmt"
	"os"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func init() {
	os.Setenv("HOME", "/root")
}

func main() {
	result, err := xtemplate.QuickExecute(
		"{{ filepath.ToSlash ( filepath.Join ( os.Getenv \"HOME\" ) .file ) }}",
		map[string]any{"file": ".bashrc"},
		funcs.Safe,     // Safe functions
		funcs.OSGetenv, // Additional OS function
	)
	if err != nil {
		panic(err)
	}
	fmt.Println(result)
}
Output:

/root/.bashrc
Example (Sixth)
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	tmpl := `
{{- define "getName" -}}
	{{- if not .user -}}
		{{ return "Anonymous" }}
	{{- end -}}
	{{- return .user.name -}}
{{- end -}}
Welcome, {{ tmpl.Exec "getName" . }}!
`

	result, err := xtemplate.QuickExecute(tmpl, map[string]any{}, funcs.Safe)
	if err != nil {
		panic(err)
	}
	fmt.Println(result)
}
Output:

Welcome, Anonymous!
Example (Third)
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	data := map[string]any{
		"users": []map[string]any{
			{"firstname": "John", "lastname": "Doe", "age": "25", "active": "true"},
			{"firstname": "Jane", "lastname": "Smith", "age": "30", "active": "false"},
		},
	}

	tmpl := `
{{- range .users -}}
Name: {{ strings.Join ( slice.NewStrings .firstname .lastname ) " " }}
Age: {{ conv.ToInt .age }}
Active: {{ conv.ToBool .active }}
---
{{ end -}}
`

	result, err := xtemplate.QuickExecute(tmpl, data, funcs.Safe)
	if err != nil {
		panic(err)
	}
	fmt.Println(result)
}
Output:

Name: John Doe
Age: 25
Active: true
---
Name: Jane Smith
Age: 30
Active: false
---

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrArgNotSlice = errors.New("argument must be a slice")

ErrArgNotSlice is returned when the argument provided is not a slice.

View Source
var ErrAtLeastOneArgumentIsRequired = errors.New("at least one argument is required")

ErrAtLeastOneArgumentIsRequired is returned when no arguments are provided to a function that requires at least one argument.

View Source
var ErrCannotCompactAnySlice = errors.New("cannot compact []any slices")

ErrCannotCompactAnySlice is returned when trying to compact a []any slice.

View Source
var ErrCannotSortAnySlice = errors.New("cannot sort []any slices")

ErrCannotSortAnySlice is returned when trying to sort a []any slice.

View Source
var ErrFirstArgumentMustBeSlice = errors.New("first argument must be a slice")

ErrFirstArgumentMustBeSlice is returned when the first argument provided is not a slice.

View Source
var ErrOnlyOneSliceIsAllowed = errors.New("only one slice argument is allowed")

ErrOnlyOneSliceIsAllowed is returned when more than one slice argument is provided to a function that only allows one slice argument.

Functions

func Execute

func Execute(t *template.Template, wr io.Writer, data any) error

Execute executes the given template with the provided data and writes the result to the given writer.

func ExecuteTemplate

func ExecuteTemplate(t *template.Template, wr io.Writer, name string, data any) error

ExecuteTemplate executes the named template within the given template with the provided data and writes the result to the given writer.

func FuncMap

func FuncMap(t *template.Template, allowedFunctions ...AllowedFunctions) template.FuncMap

FuncMap returns a template.FuncMap containing only the functions specified in allowedFunctions.

Example
package main

import (
	"os"
	"text/template"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	t := template.New("template")
	t = t.Funcs(xtemplate.FuncMap(t,
		funcs.Strings,     // allow all functions in the strings namespace
		funcs.URLJoinPath, // allow only the url.JoinPath function
	))
	t, err := t.Parse(`{{ strings.ToLower ( url.JoinPath "https://example.com" "INDEX.HTML" ) }}`)
	if err != nil {
		panic(err)
	}
	err = t.Execute(os.Stdout, nil)
	if err != nil {
		panic(err)
	}
}
Output:

https://example.com/index.html

func QuickExecute

func QuickExecute(tmplStr string, data any, allowedFunctions ...AllowedFunctions) (string, error)

QuickExecute is a convenience function to parse and execute a template string with the given data and allowed functions and write the result to the given writer.

Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		"Hello {{strings.ToLower .name}}",
		map[string]any{"name": "Joe"},
		funcs.Safe,
	)
	fmt.Println(s)
}
Output:

Hello joe
Example (Second)
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		"{{filepath.ToSlash (filepath.Join (os.Getenv \"HOME\") .file)}}",
		map[string]any{"file": ".bashrc"},
		funcs.Safe,     // Allow all safe functions
		funcs.OSGetenv, // Allow only the os.Getenv function
	)
	fmt.Println(s)
}
Output:

/root/.bashrc

Types

type AllowedFunctions

type AllowedFunctions interface {
	Functions() []funcs.Func
}

AllowedFunctions is an interface that types can implement to provide a list of allowed functions.

type Cmp

type Cmp rootContext

Cmp provides access to functions in the cmp package.

func (Cmp) Or

func (ctx Cmp) Or(s ...any) (any, error)

Or is a logical OR operator that returns the first non-zero value from the provided arguments.

Example 1:

{{ cmp.Or "" "Hello" "World" }} // Output: Hello

Example 2:

{{ cmp.Or 0 1 2 }} // Output: 1

Example 3:

{{ cmp.Or ( slice.NewStrings "" "Hello" "World" ) }} // Output: Hello
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ cmp.Or "" "Hello" "World" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

Hello
Example (Second)
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ cmp.Or 0 1 2 }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

1
Example (Third)
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ cmp.Or ( slice.NewStrings "" "Hello" "World" ) }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

Hello

type Conv

type Conv rootContext

Conv provides functions to convert between types.

func (Conv) ToBool

func (ctx Conv) ToBool(in any) (bool, error)

ToBool converts various types to bool.

Example:

{{ conv.ToBool "true" }} // Output: true
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ conv.ToBool "true" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

true

func (Conv) ToBools

func (ctx Conv) ToBools(in []any) ([]bool, error)

ToBools converts a list of various types to bools.

Example:

{{ $sl := slice.New "true" "false" 1 0 "yes" "no" }}
{{ conv.ToBools $sl }} // Output: [true false true false true false]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ $sl := slice.New "true" "false" 1 0 "yes" "no" }}
{{ conv.ToBools $sl }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[true false true false true false]

func (Conv) ToFloat32

func (ctx Conv) ToFloat32(v any) (float32, error)

ToFloat32 converts various types to float32.

Example:

{{ conv.ToFloat32 "3.14" }} // Output: 3.14
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ conv.ToFloat32 "3.14" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

3.14

func (Conv) ToFloat32s

func (ctx Conv) ToFloat32s(in []any) ([]float32, error)

ToFloat32s converts a list of various types to float32s.

Example:

{{ $sl := slice.New "3.14" 42 "1e10" }}
{{ conv.ToFloat32s $sl }} // Output: [3.14 42 1e+10]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ $sl := slice.New "3.14" 42 "1e10" }}
{{ conv.ToFloat32s $sl }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[3.14 42 1e+10]

func (Conv) ToFloat64

func (ctx Conv) ToFloat64(v any) (float64, error)

ToFloat64 converts various types to float64.

Example:

{{ conv.ToFloat64 "3.14" }} // Output: 3.14
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ conv.ToFloat64 "3.14" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

3.14

func (Conv) ToFloat64s

func (ctx Conv) ToFloat64s(in []any) ([]float64, error)

ToFloat64s converts a list of various types to float64s.

Example:

{{ $sl := slice.New "3.14" 42 "1e10" }}
{{ conv.ToFloat64s $sl }} // Output: [3.14 42 1e+10]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ $sl := slice.New "3.14" 42 "1e10" }}
{{ conv.ToFloat64s $sl }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[3.14 42 1e+10]

func (Conv) ToInt

func (ctx Conv) ToInt(v any) (int, error)

ToInt converts various types to int.

Example:

{{ conv.ToInt "42" }} // Output: 42
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ conv.ToInt "42" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

42

func (Conv) ToInt16

func (ctx Conv) ToInt16(v any) (int16, error)

ToInt16 converts various types to int16.

Example:

{{ conv.ToInt16 "42" }} // Output: 42
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ conv.ToInt16 "42" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

42

func (Conv) ToInt16s

func (ctx Conv) ToInt16s(in []any) ([]int16, error)

ToInt16s converts a list of various types to int16s.

Example:

{{ $sl := slice.New "42" 7 "0x10" }}
{{ conv.ToInt16s $sl }} // Output: [42 7 16]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ $sl := slice.New "42" 7 "0x10" }}
{{ conv.ToInt16s $sl }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[42 7 16]

func (Conv) ToInt32

func (ctx Conv) ToInt32(v any) (int32, error)

ToInt32 converts various types to int32.

Example:

{{ conv.ToInt32 "42" }} // Output: 42
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ conv.ToInt32 "42" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

42

func (Conv) ToInt32s

func (ctx Conv) ToInt32s(in []any) ([]int32, error)

ToInt32s converts a list of various types to int32s.

Example:

{{ $sl := slice.New "42" 7 "0x10" }}
{{ conv.ToInt32s $sl }} // Output: [42 7 16]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ $sl := slice.New "42" 7 "0x10" }}
{{ conv.ToInt32s $sl }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[42 7 16]

func (Conv) ToInt64

func (ctx Conv) ToInt64(v any) (int64, error)

ToInt64 converts various types to int64.

Example:

{{ conv.ToInt64 "42" }} // Output: 42
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ conv.ToInt64 "42" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

42

func (Conv) ToInt64s

func (ctx Conv) ToInt64s(in []any) ([]int64, error)

ToInt64s converts a list of various types to int64s. // Example:

{{ $sl := slice.New "42" 7 "0x10" }}
{{ conv.ToInt64s $sl }} // Output: [42 7 16]

func (Conv) ToInt8

func (ctx Conv) ToInt8(v any) (int8, error)

ToInt8 converts various types to int8.

Example:

{{ conv.ToInt8 "42" }} // Output: 42
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ conv.ToInt8 "42" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

42

func (Conv) ToInt8s

func (ctx Conv) ToInt8s(in []any) ([]int8, error)

ToInt8s converts a list of various types to int8s.

Example:

{{ $sl := slice.New "42" 7 "0x10" }}
{{ conv.ToInt8s $sl }} // Output: [42 7 16]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ $sl := slice.New "42" 7 "0x10" }}
{{ conv.ToInt8s $sl }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[42 7 16]

func (Conv) ToInts

func (ctx Conv) ToInts(in []any) ([]int, error)

ToInts converts a list of various types to ints.

Example:

{{ $sl := slice.New "42" 7 "0x10" }}
{{ conv.ToInts $sl }} // Output: [42 7 16]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ $sl := slice.New "42" 7 "0x10" }}
{{ conv.ToInts $sl }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[42 7 16]

func (Conv) ToString

func (ctx Conv) ToString(in any) (string, error)

ToString converts various types to string.

Example:

{{ conv.ToString 42 }} // Output: 42
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ conv.ToString 42 }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

42

func (Conv) ToStrings

func (ctx Conv) ToStrings(in []any) ([]string, error)

ToStrings converts a list of various types to strings.

Example:

{{ $sl := slice.New 42 true 3.14 }}
{{ conv.ToStrings $sl }} // Output: [42 true 3.14]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ $sl := slice.New 42 true 3.14 }}
{{ conv.ToStrings $sl }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[42 true 3.14]

func (Conv) ToUint

func (ctx Conv) ToUint(v any) (uint, error)

ToUint converts various types to uint.

Example:

{{ conv.ToUint "42" }} // Output: 42
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ conv.ToUint "42" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

42

func (Conv) ToUint16

func (ctx Conv) ToUint16(v any) (uint16, error)

ToUint16 converts various types to uint16.

Example:

{{ conv.ToUint16 "42" }} // Output: 42
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ conv.ToUint16 "42" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

42

func (Conv) ToUint16s

func (ctx Conv) ToUint16s(in []any) ([]uint16, error)

ToUint16s converts a list of various types to uint16s.

Example:

{{ $sl := slice.New "42" 7 "0x10" }}
{{ conv.ToUint16s $sl }} // Output: [42 7 16]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ $sl := slice.New "42" 7 "0x10" }}
{{ conv.ToUint16s $sl }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[42 7 16]

func (Conv) ToUint32

func (ctx Conv) ToUint32(v any) (uint32, error)

ToUint32 converts various types to uint32.

Example:

{{ conv.ToUint32 "42" }} // Output: 42
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ conv.ToUint32 "42" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

42

func (Conv) ToUint32s

func (ctx Conv) ToUint32s(in []any) ([]uint32, error)

ToUint32s converts a list of various types to uint32s.

Example:

{{ $sl := slice.New "42" 7 "0x10" }}
{{ conv.ToUint32s $sl }} // Output: [42 7 16]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ $sl := slice.New "42" 7 "0x10" }}
{{ conv.ToUint32s $sl }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[42 7 16]

func (Conv) ToUint64

func (ctx Conv) ToUint64(v any) (uint64, error)

ToUint64 converts various types to uint64.

Example:

{{ conv.ToUint64 "42" }} // Output: 42
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ conv.ToUint64 "42" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

42

func (Conv) ToUint64s

func (ctx Conv) ToUint64s(in []any) ([]uint64, error)

ToUint64s converts a list of various types to uint64s. // Example:

{{ $sl := slice.New "42" 7 "0x10" }}
{{ conv.ToUint64s $sl }} // Output: [42 7 16]

func (Conv) ToUint8

func (ctx Conv) ToUint8(v any) (uint8, error)

ToUint8 converts various types to uint8.

Example:

{{ conv.ToUint8 "42" }} // Output: 42
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ conv.ToUint8 "42" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

42

func (Conv) ToUint8s

func (ctx Conv) ToUint8s(in []any) ([]uint8, error)

ToUint8s converts a list of various types to uint8s.

Example:

{{ $sl := slice.New "42" 7 "0x10" }}
{{ conv.ToUint8s $sl }} // Output: [42 7 16]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ $sl := slice.New "42" 7 "0x10" }}
{{ conv.ToUint8s $sl }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[42 7 16]

func (Conv) ToUints

func (ctx Conv) ToUints(in []any) ([]uint, error)

ToUints converts a list of various types to uints.

Example:

{{ $sl := slice.New "42" 7 "0x10" }}
{{ conv.ToUints $sl }} // Output: [42 7 16]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ $sl := slice.New "42" 7 "0x10" }}
{{ conv.ToUints $sl }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[42 7 16]

type CustomError added in v0.1.1

type CustomError struct {
	Message string
}

CustomError represents a custom error with a message.

func (CustomError) Error added in v0.1.1

func (e CustomError) Error() string

type CutPrefixResult

type CutPrefixResult struct {
	After string
	Found bool
}

CutPrefixResult is the result type for the CutPrefix function.

type CutResult

type CutResult struct {
	Before string
	After  string
	Found  bool
}

CutResult is the result type for the Cut function.

type CutSuffixResult

type CutSuffixResult struct {
	Before string
	Found  bool
}

CutSuffixResult is the result type for the CutSuffix function.

type Dict

type Dict rootContext

Dict provides helper functions for dictionaries.

func (Dict) HasKey

func (ctx Dict) HasKey(m map[any]any, key any) (bool, error)

HasKey checks if a map contains a given key.

Example 1:

{{ dict.HasKey (dict.New "name" "Frank" "age" 42) "name" }} // Output: true

Example 2:

{{ dict.HasKey (dict.New "name" "Frank" "age" 42) "email" }} // Output: false
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ dict.HasKey (dict.New "name" "Frank" "age" 42) "name" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

true
Example (Second)
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ dict.HasKey (dict.New "name" "Frank" "age" 42) "email" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

false

func (Dict) HasValue

func (ctx Dict) HasValue(m map[any]any, value any) (bool, error)

HasValue checks if a map contains a given value.

Example 1:

{{ dict.HasValue (dict.New "name" "Frank" "age" 42) 42 }} // Output: true

Example 2:

{{ dict.HasValue (dict.New "name" "Frank" "age" 42) "Joe" }} // Output: false
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ dict.HasValue (dict.New "name" "Frank" "age" 42) 42 }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

true
Example (Second)
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ dict.HasValue (dict.New "name" "Frank" "age" 42) "Joe" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

false

func (Dict) IsEmpty added in v0.1.1

func (ctx Dict) IsEmpty(m map[any]any) (bool, error)

IsEmpty checks if a map is empty.

Example:

{{ dict.IsEmpty (dict.New) }} // Output: true
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ dict.IsEmpty (dict.New) }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

true

func (Dict) Keys

func (ctx Dict) Keys(m map[any]any) ([]any, error)

Keys returns the keys of a map as a slice.

Example:

{{ $dict := dict.New "name" "Frank" "age" 42 }}
{{ $keys := conv.ToStrings ( dict.Keys $dict ) }}
{{ slice.Sort $keys }} // Output: [age name]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ $dict := dict.New "name" "Frank" "age" 42 }}
{{ $keys := conv.ToStrings ( dict.Keys $dict ) }}
{{ slice.Sort $keys }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[age name]

func (Dict) New

func (ctx Dict) New(vals ...any) (map[any]any, error)

New creates a map from a list of key/value pairs.

Example:

{{ dict.New "name" "Frank" "age" 42 }} // Output: map[age:42 name:Frank]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ dict.New "name" "Frank" "age" 42 }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

map[age:42 name:Frank]

type FilePath

type FilePath rootContext

FilePath provides access to functions in the path/filepath package.

func (FilePath) Abs

func (ctx FilePath) Abs(s string) (string, error)

Abs returns an absolute representation of path. If the path is not absolute it will be joined with the current working directory to turn it into an absolute path.

Example:

{{ filepath.Abs "foo/bar" }}

func (FilePath) Base

func (ctx FilePath) Base(s string) (string, error)

Base returns the last element of path. Trailing path separators are removed before extracting the last element. If the path is empty, Base returns ".". If the path consists entirely of separators, Base returns a single separator.

Example:

{{ filepath.Base "/foo/bar/baz.js" }}

func (FilePath) Clean

func (ctx FilePath) Clean(s string) (string, error)

Clean returns the shortest path name equivalent to path by purely lexical processing. It applies the following rules iteratively until no further processing can be done.

Example:

{{ filepath.Clean "/foo//bar/../baz" }}

func (FilePath) Dir

func (ctx FilePath) Dir(s string) (string, error)

Dir returns all but the last element of path, typically the path's directory. After dropping the final element, Dir calls Clean on the path and trailing slashes are removed.

Example:

{{ filepath.Dir "/foo/bar/baz.js" }}

func (FilePath) Ext

func (ctx FilePath) Ext(s string) (string, error)

Ext returns the file name extension used by path. The extension is the suffix beginning at the final dot in the final element of path; it is empty if there is no dot.

Example:

{{ filepath.Ext "/foo/bar/baz.js" }}

func (FilePath) FromSlash added in v0.1.1

func (ctx FilePath) FromSlash(path string) (string, error)

FromSlash returns the result of replacing each slash ('/') character in path with a separator character. Multiple slashes are replaced by multiple separators. The result is not Cleaned.

Example:

{{ filepath.FromSlash "foo/bar/baz" }}

func (FilePath) Join

func (ctx FilePath) Join(s ...string) (string, error)

Join joins any number of path elements into a single path, separating them with an OS specific Separator. Empty elements are ignored. The result is Cleaned.

Example:

{{ filepath.Join "foo" "bar" "baz" }}

func (FilePath) Rel

func (ctx FilePath) Rel(basepath, targetpath string) (string, error)

Rel returns a relative path that is lexically equivalent to targetpath when joined to basepath with an intervening separator. That is, Join(basepath, Rel(basepath, targetpath)) is equivalent to targetpath itself.

Example:

{{ filepath.Rel "/a" "/a/b/c" }}

func (FilePath) ToSlash added in v0.1.1

func (ctx FilePath) ToSlash(path string) (string, error)

ToSlash returns the result of replacing each separator character in path with a slash ('/') character. Multiple separators are replaced by multiple slashes. The result is not Cleaned.

Example:

{{ filepath.ToSlash "foo\bar\baz" }}

type FuncNotAllowedError

type FuncNotAllowedError struct {
	Func funcs.Func
}

FuncNotAllowedError is returned when a function is called that is not in the allowed function set.

func (*FuncNotAllowedError) Error

func (e *FuncNotAllowedError) Error() string

type JSON

type JSON rootContext

JSON provides access to functions in the encoding/json package.

func (JSON) Compact

func (ctx JSON) Compact(dst *bytes.Buffer, src []byte) error

Compact appends to dst the JSON-encoded src with insignificant space characters elided.

Example:

{{ json.Compact .Buffer .JSONBytes }}

func (JSON) HTMLEscape

func (ctx JSON) HTMLEscape(dst *bytes.Buffer, src []byte) error

HTMLEscape appends to dst the JSON-encoded src with <, >, &, U+2028 and U+2029 characters inside string literals changed to \u003c, \u003e, \u0026, \u2028, \u2029 so that the JSON will be safe to embed inside HTML <script> tags. For historical reasons, web browsers don't honor the standard HTML escaping rules within <script> tags, but they do honor the JSON backslash escaping, and the JSON specification allows backslash-escaping of these characters, so this function enables JSON to be safely placed inside HTML <script> tags. HTMLEscape only affects the contents of string literals in the JSON. It has no effect on the structural characters of the JSON itself.

Example:

{{ json.HTMLEscape .Buffer .JSONBytes }}

func (JSON) Indent

func (ctx JSON) Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error

Indent appends to dst an indented form of the JSON-encoded src. Each element in a JSON object or array begins on a new line, indented according to the indentation nesting. The data appended to dst does not begin with the prefix nor any indentation, to make it easier to embed inside other formatted JSON data. Although leading space characters (space, tab, carriage return, newline) at the beginning of src are dropped, trailing space characters at the end of src are preserved and copied to dst. For example, if src has no trailing spaces, neither will dst; if src ends in a trailing newline, so will dst.

Example:

{{ json.Indent .Buffer .JSONBytes "" "  " }}

func (JSON) Marshal

func (ctx JSON) Marshal(v any) ([]byte, error)

Marshal returns the JSON encoding of v.

Example:

{{ $dict := dict.New "foo" "bar" }}
{{ $buf := json.Marshal $dict }}
{{ conv.ToString $buf }} // Output: {"foo":"bar"}
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ $dict := dict.New "foo" "bar" }}
{{ $buf := json.Marshal $dict }}
{{ conv.ToString $buf }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

{"foo":"bar"}

func (JSON) MarshalIndent

func (ctx JSON) MarshalIndent(v any, prefix, indent string) ([]byte, error)

MarshalIndent is like Marshal but applies Indent to format the output. Each JSON element in the output will begin on a new line beginning with prefix followed by one or more copies of indent according to the indentation nesting.

Example:

{{ json.MarshalIndent .Data "" "  " }}

func (JSON) Unmarshal

func (ctx JSON) Unmarshal(data []byte, v any) error

Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError.

Example:

{{ json.Unmarshal .JSONBytes .Target }}

func (JSON) Valid

func (ctx JSON) Valid(data []byte) (bool, error)

Valid reports whether data is a valid JSON encoding.

Example:

{{ json.Valid .JSONBytes }}

type OS

type OS rootContext

OS provides access to functions in the os package.

func (OS) Chdir

func (ctx OS) Chdir(dir string) error

Chdir changes the current working directory to the named directory. If there is an error, it will be of type *PathError.

Example:

{{ os.Chdir "/tmp" }}

func (OS) Chmod

func (ctx OS) Chmod(name string, mode os.FileMode) error

Chmod changes the mode of the named file to mode. If the file is a symbolic link, it changes the mode of the link's target.

Example:

{{ os.Chmod "file.txt" 0644 }}

func (OS) Chown

func (ctx OS) Chown(name string, uid, gid int) error

Chown changes the numeric uid and gid of the named file. If the file is a symbolic link, it changes the uid and gid of the link's target.

Example:

{{ os.Chown "file.txt" 1000 1000 }}

func (OS) Chtimes

func (ctx OS) Chtimes(name string, atime time.Time, mtime time.Time) error

Chtimes changes the access and modification times of the named file, similar to the Unix utime() or utimes() functions.

Example:

{{ os.Chtimes "file.txt" .AccessTime .ModTime }}

func (OS) Clearenv

func (ctx OS) Clearenv() error

Clearenv deletes all environment variables.

Example:

{{ os.Clearenv }}

func (OS) Environ

func (ctx OS) Environ() ([]string, error)

Environ returns a copy of strings representing the environment, in the form "key=value".

Example:

{{ os.Environ }}

func (OS) Executable

func (ctx OS) Executable() (string, error)

Executable returns the path name for the executable that started the current process.

Example:

{{ os.Executable }}

func (OS) Exit

func (ctx OS) Exit(code int) error

Exit causes the current program to exit with the given status code. Conventionally, code zero indicates success, non-zero an error.

Example:

{{ os.Exit 0 }}

func (OS) Expand

func (ctx OS) Expand(s string, mapping func(string) string) (string, error)

Expand replaces ${var} or $var in the string based on the mapping function. For example, os.ExpandEnv(s) is equivalent to os.Expand(s, os.Getenv).

Example:

{{ os.Expand "$HOME/file" .MappingFunc }}

func (OS) ExpandEnv

func (ctx OS) ExpandEnv(s string) (string, error)

ExpandEnv replaces ${var} or $var in the string according to the values of the current environment variables.

Example:

{{ os.ExpandEnv "$HOME/file" }}

func (OS) Getegid

func (ctx OS) Getegid() (int, error)

Getegid returns the numeric effective group id of the caller. On Windows, it returns -1.

Example:

{{ os.Getegid }}

func (OS) Getenv

func (ctx OS) Getenv(key string) (string, error)

Getenv retrieves the value of the environment variable named by the key. It returns the value, which will be empty if the variable is not present.

Example:

{{ os.Getenv "HOME" }}

func (OS) Geteuid

func (ctx OS) Geteuid() (int, error)

Geteuid returns the numeric effective user id of the caller. On Windows, it returns -1.

Example:

{{ os.Geteuid }}

func (OS) Getgid

func (ctx OS) Getgid() (int, error)

Getgid returns the numeric group id of the caller. On Windows, it returns -1.

Example:

{{ os.Getgid }}

func (OS) Getgroups

func (ctx OS) Getgroups() ([]int, error)

Getgroups returns a list of the numeric ids of groups that the caller belongs to.

Example:

{{ os.Getgroups }}

func (OS) Getpagesize

func (ctx OS) Getpagesize() (int, error)

Getpagesize returns the underlying system's memory page size.

Example:

{{ os.Getpagesize }}

func (OS) Getpid

func (ctx OS) Getpid() (int, error)

Getpid returns the process id of the caller.

Example:

{{ os.Getpid }}

func (OS) Getppid

func (ctx OS) Getppid() (int, error)

Getppid returns the process id of the caller's parent.

Example:

{{ os.Getppid }}

func (OS) Getuid

func (ctx OS) Getuid() (int, error)

Getuid returns the numeric user id of the caller. On Windows, it returns -1.

Example:

{{ os.Getuid }}

func (OS) Getwd

func (ctx OS) Getwd() (string, error)

Getwd returns a rooted path name corresponding to the current directory.

Example:

{{ os.Getwd }}

func (OS) Hostname

func (ctx OS) Hostname() (string, error)

Hostname returns the host name reported by the kernel.

Example:

{{ os.Hostname }}

func (OS) IsExist

func (ctx OS) IsExist(err error) (bool, error)

IsExist returns a boolean indicating whether the error is known to report that a file or directory already exists.

Example:

{{ os.IsExist .Error }}

func (OS) IsNotExist

func (ctx OS) IsNotExist(err error) (bool, error)

IsNotExist returns a boolean indicating whether the error is known to report that a file or directory does not exist.

Example:

{{ os.IsNotExist .Error }}

func (OS) IsPathSeparator

func (ctx OS) IsPathSeparator(c uint8) (bool, error)

IsPathSeparator reports whether c is a directory separator character.

Example:

{{ os.IsPathSeparator 47 }}

func (OS) IsPermission

func (ctx OS) IsPermission(err error) (bool, error)

IsPermission returns a boolean indicating whether the error is known to report that permission is denied.

Example:

{{ os.IsPermission .Error }}

func (OS) IsTimeout

func (ctx OS) IsTimeout(err error) (bool, error)

IsTimeout returns a boolean indicating whether the error is known to report that a timeout occurred.

Example:

{{ os.IsTimeout .Error }}

func (OS) Lchown

func (ctx OS) Lchown(name string, uid, gid int) error

Lchown changes the numeric uid and gid of the named file. If the file is a symbolic link, it changes the uid and gid of the link itself.

Example:

{{ os.Lchown "file.txt" 1000 1000 }}
func (ctx OS) Link(oldname, newname string) error

Link creates newname as a hard link to the oldname file.

Example:

{{ os.Link "oldfile" "newfile" }}

func (OS) LookupEnv

func (ctx OS) LookupEnv(key string) (string, bool, error)

LookupEnv retrieves the value of the environment variable named by the key. If the variable is present in the environment the value (which may be empty) is returned and the boolean is true. Otherwise the returned value will be empty and the boolean will be false.

Example:

{{ os.LookupEnv "HOME" }}

func (OS) Mkdir

func (ctx OS) Mkdir(name string, perm os.FileMode) error

Mkdir creates a new directory with the specified name and permission bits (before umask).

Example:

{{ os.Mkdir "newdir" 0755 }}

func (OS) MkdirAll

func (ctx OS) MkdirAll(path string, perm os.FileMode) error

MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error.

Example:

{{ os.MkdirAll "path/to/dir" 0755 }}

func (OS) MkdirTemp

func (ctx OS) MkdirTemp(dir, pattern string) (string, error)

MkdirTemp creates a new temporary directory in the directory dir and returns the pathname of the new directory.

Example:

{{ os.MkdirTemp "/tmp" "pattern" }}

func (OS) NewSyscallError

func (ctx OS) NewSyscallError(syscall string, err error) (error, error)

NewSyscallError returns, as an error, a new SyscallError with the given system call name and error details.

Example:

{{ os.NewSyscallError "open" .Error }}

func (OS) Pipe

func (ctx OS) Pipe() (*os.File, *os.File, error)

Pipe returns a connected pair of Files; reads from r return bytes written to w.

Example:

{{ os.Pipe }}

func (OS) ReadFile

func (ctx OS) ReadFile(name string) ([]byte, error)

ReadFile reads the named file and returns the contents.

Example:

{{ os.ReadFile "file.txt" }}
func (ctx OS) Readlink(name string) (string, error)

Readlink returns the destination of the named symbolic link.

Example:

{{ os.Readlink "symlink" }}

func (OS) Remove

func (ctx OS) Remove(name string) error

Remove removes the named file or (empty) directory.

Example:

{{ os.Remove "file.txt" }}

func (OS) RemoveAll

func (ctx OS) RemoveAll(path string) error

RemoveAll removes path and any children it contains. It removes everything it can but returns the first error it encounters.

Example:

{{ os.RemoveAll "path/to/dir" }}

func (OS) Rename

func (ctx OS) Rename(oldpath, newpath string) error

Rename renames (moves) oldpath to newpath. If newpath already exists and is not a directory, Rename replaces it.

Example:

{{ os.Rename "oldname" "newname" }}

func (OS) SameFile

func (ctx OS) SameFile(fi1, fi2 os.FileInfo) (bool, error)

SameFile reports whether fi1 and fi2 describe the same file.

Example:

{{ os.SameFile .FileInfo1 .FileInfo2 }}

func (OS) Setenv

func (ctx OS) Setenv(key, value string) error

Setenv sets the value of the environment variable named by the key.

Example:

{{ os.Setenv "KEY" "value" }}
func (ctx OS) Symlink(oldname, newname string) error

Symlink creates newname as a symbolic link to oldname.

Example:

{{ os.Symlink "oldname" "newname" }}

func (OS) TempDir

func (ctx OS) TempDir() (string, error)

TempDir returns the default directory to use for temporary files.

Example:

{{ os.TempDir }}

func (OS) Truncate

func (ctx OS) Truncate(name string, size int64) error

Truncate changes the size of the named file.

Example:

{{ os.Truncate "file.txt" 100 }}

func (OS) Unsetenv

func (ctx OS) Unsetenv(key string) error

Unsetenv unsets a single environment variable.

Example:

{{ os.Unsetenv "KEY" }}

func (OS) UserCacheDir

func (ctx OS) UserCacheDir() (string, error)

UserCacheDir returns the default root directory to use for user-specific cached data.

Example:

{{ os.UserCacheDir }}

func (OS) UserConfigDir

func (ctx OS) UserConfigDir() (string, error)

UserConfigDir returns the default root directory to use for user-specific configuration data.

Example:

{{ os.UserConfigDir }}

func (OS) UserHomeDir

func (ctx OS) UserHomeDir() (string, error)

UserHomeDir returns the current user's home directory.

Example:

{{ os.UserHomeDir }}

func (OS) WriteFile

func (ctx OS) WriteFile(name string, data []byte, perm os.FileMode) error

WriteFile writes data to the named file, creating it if necessary.

Example:

{{ os.WriteFile "file.txt" .Data 0644 }}

type OnlyOneArgumentIsAllowedError added in v0.1.2

type OnlyOneArgumentIsAllowedError struct{}

OnlyOneArgumentIsAllowedError indicates that only one argument is allowed.

func (OnlyOneArgumentIsAllowedError) Error added in v0.1.2

type Path

type Path rootContext

Path provides access to functions in the path package.

func (Path) Base

func (ctx Path) Base(s string) (string, error)

Base returns the last element of path. Trailing slashes are removed before extracting the last element. If the path is empty, Base returns ".". If the path consists entirely of slashes, Base returns "/".

Example:

{{ path.Base "/foo/bar/baz" }} // Output: baz
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ path.Base "/foo/bar/baz" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

baz

func (Path) Clean

func (ctx Path) Clean(s string) (string, error)

Clean returns the shortest path name equivalent to path by purely lexical processing. It applies the following rules iteratively until no further processing can be done.

Example:

{{ path.Clean "/foo//bar/../baz" }} // Output: /foo/baz
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ path.Clean "/foo//bar/../baz" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

/foo/baz

func (Path) Dir

func (ctx Path) Dir(s string) (string, error)

Dir returns all but the last element of path, typically the path's directory. After dropping the final element, Dir calls Clean on the path and trailing slashes are removed. If the path is empty, Dir returns ".".

Example:

{{ path.Dir "/foo/bar/baz" }} // Output: /foo/bar
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ path.Dir "/foo/bar/baz" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

/foo/bar

func (Path) Ext

func (ctx Path) Ext(s string) (string, error)

Ext returns the file name extension used by path. The extension is the suffix beginning at the final dot in the final slash-separated element of path; it is empty if there is no dot.

Example:

{{ path.Ext "/foo/bar/baz.js" }} // Output: .js
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ path.Ext "/foo/bar/baz.js" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

.js

func (Path) Join

func (ctx Path) Join(s ...string) (string, error)

Join joins any number of path elements into a single path, separating them with slashes. Empty elements are ignored. The result is Cleaned.

Example:

{{ path.Join "foo" "bar" "baz" }} // Output: foo/bar/baz
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ path.Join "foo" "bar" "baz" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

foo/bar/baz

type Regexp

type Regexp rootContext

Regexp provides access to functions in the regexp package.

func (Regexp) FindAllString

func (ctx Regexp) FindAllString(pattern string, s string, n int) ([]string, error)

FindAllString returns a slice of all successive matches of the expression, as defined by the 'All' description in the package comment. A return value of nil indicates no match.

Example:

{{ regexp.FindAllString "p([a-z]+)ch" "peach punch pinch" -1 }} // Output: [peach punch pinch]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ regexp.FindAllString "p([a-z]+)ch" "peach punch pinch" -1 }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[peach punch pinch]

func (Regexp) FindAllStringIndex

func (ctx Regexp) FindAllStringIndex(pattern string, s string, n int) ([][]int, error)

FindAllStringIndex returns a slice of all successive matches of the expression, as defined by the 'All' description in the package comment. A return value of nil indicates no match.

Example:

{{ regexp.FindAllStringIndex "p([a-z]+)ch" "peach punch" -1 }} // Output: [[0 5] [6 11]]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ regexp.FindAllStringIndex "p([a-z]+)ch" "peach punch" -1 }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[[0 5] [6 11]]

func (Regexp) FindAllStringSubmatch

func (ctx Regexp) FindAllStringSubmatch(pattern string, s string, n int) ([][]string, error)

FindAllStringSubmatch returns a slice of all successive matches of the expression, as defined by the 'All' description in the package comment. A return value of nil indicates no match.

Example 1:

{{ regexp.FindAllStringSubmatch "a(x*)b" "-ab-" -1 }} // Output: [[ab ]]

Example 2:

{{ regexp.FindAllStringSubmatch "a(x*)b" "-axxb-" -1 }} // [[axxb xx]]

Example 3:

{{ regexp.FindAllStringSubmatch "a(x*)b" "-ab-axb-" -1 }} // [[ab ] [axb x]]

Example 4:

{{ regexp.FindAllStringSubmatch "a(x*)b" "-axxb-ab-" -1 }} // Output: [[axxb xx] [ab ]]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ regexp.FindAllStringSubmatch "a(x*)b" "-ab-" -1 }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[[ab ]]
Example (Second)
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ regexp.FindAllStringSubmatch "a(x*)b" "-axxb-ab-" -1 }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[[axxb xx] [ab ]]

func (Regexp) FindAllStringSubmatchIndex

func (ctx Regexp) FindAllStringSubmatchIndex(pattern string, s string, n int) ([][]int, error)

FindAllStringSubmatchIndex returns a slice of all successive matches of the expression, as defined by the 'All' description in the package comment. A return value of nil indicates no match.

Example 1:

{{ regexp.FindAllStringSubmatchIndex "a(x*)b" "-ab-" -1 }} // Output: [[1 3 2 2]]

Example 2:

{{ regexp.FindAllStringSubmatchIndex "a(x*)b" "-axxb-" -1 }} // Output: [[1 5 2 4]]

Example 3:

{{ regexp.FindAllStringSubmatchIndex "a(x*)b" "-ab-axb-" -1 }} // Output: [[1 3 2 2] [4 7 5 6]]

Example 4:

{{ regexp.FindAllStringSubmatchIndex "a(x*)b" "-axxb-ab-" -1 }} // Output: [[1 5 2 4] [6 8 7 7]]

Example 5:

{{ regexp.FindAllStringSubmatchIndex "a(x*)b" "-foo-" -1 }} // Output: []
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ regexp.FindAllStringSubmatchIndex "a(x*)b" "-ab-" -1 }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[[1 3 2 2]]
Example (Fifth)
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ regexp.FindAllStringSubmatchIndex "a(x*)b" "-foo-" -1 }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[]
Example (Fourth)
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ regexp.FindAllStringSubmatchIndex "a(x*)b" "-axxb-ab-" -1 }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[[1 5 2 4] [6 8 7 7]]
Example (Second)
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ regexp.FindAllStringSubmatchIndex "a(x*)b" "-axxb-" -1 }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[[1 5 2 4]]
Example (Third)
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ regexp.FindAllStringSubmatchIndex "a(x*)b" "-ab-axb-" -1 }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[[1 3 2 2] [4 7 5 6]]

func (Regexp) FindString

func (ctx Regexp) FindString(pattern string, s string) (string, error)

FindString returns a string holding the text of the leftmost match in s of the regular expression. If there is no match, the return value is an empty string.

Example:

{{ regexp.FindString "p([a-z]+)ch" "peach punch pinch" }} // Output: peach
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ regexp.FindString "p([a-z]+)ch" "peach punch pinch" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

peach

func (Regexp) FindStringIndex

func (ctx Regexp) FindStringIndex(pattern string, s string) ([]int, error)

FindStringIndex returns a two-element slice of integers defining the location of the leftmost match in s of the regular expression. The match itself is at s[loc[0]:loc[1]]. A return value of nil indicates no match.

Example:

{{ regexp.FindStringIndex "p([a-z]+)ch" "peach punch" }} // Output: [0 5]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ regexp.FindStringIndex "p([a-z]+)ch" "peach punch" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[0 5]

func (Regexp) FindStringSubmatch

func (ctx Regexp) FindStringSubmatch(pattern string, s string) ([]string, error)

FindStringSubmatch returns a slice of strings holding the text of the leftmost match of the regular expression in s and the matches, if any, of its subexpressions. A return value of nil indicates no match.

Example1:

{{ regexp.FindStringSubmatch "a(x*)b(y|z)c" "-axxxbyc-" }} // Output: [axxxbyc xxx y]

Example 2:

{{ regexp.FindStringSubmatch "a(x*)b(y|z)c" "-abzc-" }} // Output: [abzc  z]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ regexp.FindStringSubmatch "a(x*)b(y|z)c" "-axxxbyc-" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[axxxbyc xxx y]
Example (Second)
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ regexp.FindStringSubmatch "a(x*)b(y|z)c" "-abzc-" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[abzc  z]

func (Regexp) FindStringSubmatchIndex

func (ctx Regexp) FindStringSubmatchIndex(pattern string, s string) ([]int, error)

FindStringSubmatchIndex returns a slice of integers holding the text of the leftmost match of the regular expression in s and the matches, if any, of its subexpressions. A return value of nil indicates no match.

Example:

{{ regexp.FindStringSubmatchIndex "p([a-z]+)ch" "peach" }} // Output: [0 5 1 3]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ regexp.FindStringSubmatchIndex "p([a-z]+)ch" "peach" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[0 5 1 3]

func (Regexp) MatchString

func (ctx Regexp) MatchString(pattern string, s string) (bool, error)

MatchString reports whether the string s contains any match of the regular expression pattern.

Example 1:

{{ regexp.MatchString "p([a-z]+)ch" "peach" }} // Output: true

Example 2:

{{ regexp.MatchString "p([a-z]+)ch" "apple" }} // Output: false
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ regexp.MatchString "p([a-z]+)ch" "peach" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

true
Example (Second)
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ regexp.MatchString "p([a-z]+)ch" "apple" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

false

func (Regexp) QuoteMeta

func (ctx Regexp) QuoteMeta(s string) (string, error)

QuoteMeta returns a string that escapes all regular expression metacharacters inside the argument text; the returned string is a regular expression matching the literal text.

Example:

{{ regexp.QuoteMeta "Escaping $5.00?" }} // Output: Escaping \$5\.00\?
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ regexp.QuoteMeta "Escaping $5.00?" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

Escaping \$5\.00\?

func (Regexp) ReplaceAllLiteralString

func (ctx Regexp) ReplaceAllLiteralString(pattern string, s string, repl string) (string, error)

ReplaceAllLiteralString returns a copy of s, replacing matches of the Regexp with the replacement string repl. The replacement repl is substituted directly, without using Expand.

Example:

{{ regexp.ReplaceAllLiteralString "a(x*)b" "-ab-axxb-" "T" }} // Output: -T-T-
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ regexp.ReplaceAllLiteralString "a(x*)b" "-ab-axxb-" "T" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

-T-T-

func (Regexp) ReplaceAllString

func (ctx Regexp) ReplaceAllString(pattern string, s string, repl string) (string, error)

ReplaceAllString returns a copy of s, replacing matches of the Regexp with the replacement string repl. Inside repl, $ signs are interpreted as in Expand, so for instance $1 represents the text of the first submatch.

Example:

{{ regexp.ReplaceAllString "a(x*)b" "-ab-axxb-" "${1}W" }} // Output: -W-xxW-
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ regexp.ReplaceAllString "a(x*)b" "-ab-axxb-" "${1}W" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

-W-xxW-

func (Regexp) Split

func (ctx Regexp) Split(pattern string, s string, n int) ([]string, error)

Split slices s into substrings separated by the expression and returns a slice of the substrings between those expression matches.

Example 1:

{{ regexp.Split "a" "banana" -1 }} // Output: [b n n ]

Example 2:

{{ regexp.Split "a" "apple" 0 }} // Output: []

Example 3:

{{ regexp.Split "a" "grape" 1 }} // Output: [grape]

Example 4:

{{ regexp.Split "z+" "pizza" 2 }} // Output: [pi a]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ regexp.Split "a" "banana" -1 }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[b n n ]
Example (Fourth)
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ regexp.Split "z+" "pizza" 2 }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[pi a]
Example (Second)
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ regexp.Split "a" "apple" 0 }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[]
Example (Third)
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ regexp.Split "a" "grape" 1 }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[grape]

type ReturnError

type ReturnError struct {
	Value any
}

ReturnError is used to short-circuit template execution and return a value.

func (ReturnError) Error

func (r ReturnError) Error() string

type Slice

type Slice rootContext

Slice provides helper functions for slices.

func (Slice) Append

func (ctx Slice) Append(s any, vals ...any) (any, error)

Append appends the provided values to the slice.

Example:

{{ $sl := slice.NewStrings "Joe" }}
{{ slice.Append $sl "Alice" "Bob" }} // Output: [Joe Alice Bob]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ $sl := slice.NewStrings "Joe" }}
{{ slice.Append $sl "Alice" "Bob" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[Joe Alice Bob]

func (Slice) Compact

func (ctx Slice) Compact(s any) (any, error)

Compact replaces consecutive runs of equal elements with a single copy. This is like the uniq command found on Unix.

Example:

{{ slice.Compact ( slice.NewStrings "Hello" "Hello" "World" "World" ) }} // Output: [Hello World]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ slice.Compact ( slice.NewStrings "Hello" "Hello" "World" "World" ) }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[Hello World]

func (Slice) Contains

func (ctx Slice) Contains(s any, v any) (bool, error)

Contains checks if the slice contains the provided value.

Example:

{{ $sl := slice.NewStrings "Hello" "World" }}
{{ slice.Contains $sl "World" }} // Output: true
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ $sl := slice.NewStrings "Hello" "World" }}
{{ slice.Contains $sl "World" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

true

func (Slice) IsEmpty added in v0.1.1

func (ctx Slice) IsEmpty(s any) (bool, error)

IsEmpty checks if the provided slice is empty.

Example:

{{ $sl := slice.NewStrings }}
{{ slice.IsEmpty $sl }} // Output: true
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ $sl := slice.NewStrings }}
{{ slice.IsEmpty $sl }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

true

func (Slice) Len

func (ctx Slice) Len(s any) (int, error)

Len returns the length of the provided slice.

Example:

{{ $sl := slice.NewStrings "Hello" "World" }}
{{ slice.Len $sl }} // Output: 2
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ $sl := slice.NewStrings "Hello" "World" }}
{{ slice.Len $sl }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

2

func (Slice) New

func (ctx Slice) New(vals ...any) ([]any, error)

New creates a slice from the provided values.

Example:

{{ slice.New 1 "Hello" false }}

func (Slice) NewBools

func (ctx Slice) NewBools(vals ...any) ([]bool, error)

NewBools creates an int64 slice from the provided values.

Example:

{{ slice.NewBools false true }}

func (Slice) NewFloat64s

func (ctx Slice) NewFloat64s(vals ...any) ([]float64, error)

NewFloat64s creates an int64 slice from the provided values.

Example:

{{ slice.NewFloat64s 1.5 2.1 }}

func (Slice) NewInt64s

func (ctx Slice) NewInt64s(vals ...any) ([]int64, error)

NewInt64s creates an int64 slice from the provided values.

Example:

{{ slice.NewInt64s 1 2 }}

func (Slice) NewInts

func (ctx Slice) NewInts(vals ...any) ([]int, error)

NewInts creates an int slice from the provided values.

Example:

{{ slice.NewInts 1 2 }}

func (Slice) NewStrings

func (ctx Slice) NewStrings(vals ...any) ([]string, error)

NewStrings creates a string slice from the provided values.

Example:

{{ slice.NewStrings "Hello" "World" }}

func (Slice) Prepend

func (ctx Slice) Prepend(s any, vals ...any) (any, error)

Prepend appends the provided values to the slice.

Example:

{{ $sl := slice.NewStrings "Joe" }}
{{ slice.Prepend $sl "Alice" "Bob" }} // Output: [Alice Bob Joe]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ $sl := slice.NewStrings "Joe" }}
{{ slice.Prepend $sl "Alice" "Bob" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[Alice Bob Joe]

func (Slice) Reverse

func (ctx Slice) Reverse(s any) (any, error)

Reverse reverses the order of elements in the provided slice.

Example:

{{ slice.Reverse ( slice.NewStrings "Hello" "World" ) }} // Output: [World Hello]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ slice.Reverse ( slice.NewStrings "Hello" "World" ) }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[World Hello]

func (Slice) Sort

func (ctx Slice) Sort(s any) (any, error)

Sort sorts the provided slice.

Example:

{{ slice.Sort ( slice.NewStrings "World" "Hello" ) }} // Output: [Hello World]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ slice.Sort ( slice.NewStrings "World" "Hello" ) }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[Hello World]

func (Slice) Unique

func (ctx Slice) Unique(s any) (any, error)

Unique removes duplicate elements from the provided slice. Example:

{{ slice.Unique ( slice.NewStrings "Hello" "World" "Hello" ) }} // Output: [Hello World]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ slice.Unique ( slice.NewStrings "Hello" "World" "Hello" ) }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[Hello World]

type Strings

type Strings rootContext

Strings provides access to functions in the strings package.

func (Strings) Compare

func (ctx Strings) Compare(a, b string) (int, error)

Compare compares two strings lexicographically and returns an integer comparing two strings. The result will be 0 if a==b, -1 if a < b, and +1 if a > b.

Example 1:

{{ strings.Compare "apple" "banana" }} // Output: -1

Example 2:

{{ strings.Compare "banana" "apple" }} // Output: 1

Example 3:

{{ strings.Compare "apple" "apple" }}  // Output: 0
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.Compare "apple" "banana" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

-1
Example (Second)
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.Compare "banana" "apple" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

1
Example (Third)
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.Compare "apple" "apple" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

0

func (Strings) Contains

func (ctx Strings) Contains(s, substr string) (bool, error)

Contains reports whether substr is within s.

Example 1:

{{ strings.Contains "hello world" "world" }} // Output: true

Example 2:

{{ strings.Contains "hello world" "mars" }}  // Output: false
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.Contains "hello world" "world" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

true
Example (Second)
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.Contains "hello world" "mars" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

false

func (Strings) ContainsAny

func (ctx Strings) ContainsAny(s, chars string) (bool, error)

ContainsAny reports whether any Unicode code points in chars are within s.

Example 1:

{{ strings.ContainsAny "hello" "aeiou" }} // Output: true

Example 2:

{{ strings.ContainsAny "rhythm" "aeiou" }} // Output: false
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.ContainsAny "hello" "aeiou" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

true
Example (Second)
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.ContainsAny "rhythm" "aeiou" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

false

func (Strings) ContainsRune

func (ctx Strings) ContainsRune(s string, r rune) (bool, error)

ContainsRune reports whether the Unicode code point r is within s.

Example 1:

{{ strings.ContainsRune "hello" 'e' }} // Output: true

Example 2:

{{ strings.ContainsRune "hello" 'a' }} // Output: false
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.ContainsRune "hello" 'e' }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

true
Example (Second)
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.ContainsRune "hello" 'a' }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

false

func (Strings) Count

func (ctx Strings) Count(s, substr string) (int, error)

Count counts the number of non-overlapping instances of substr in s. If substr is an empty string, Count returns 1 + the number of Unicode code points in s.

Example 1:

{{ strings.Count "hello hello" "hello" }} // Output: 2

Example 2:

{{ strings.Count "hello" "l" }}           // Output: 2

Example 3:

{{ strings.Count "hello" "" }}            // Output: 6
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.Count "hello hello" "hello" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

2
Example (Second)
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.Count "hello" "l" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

2
Example (Third)
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.Count "hello" "" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

6

func (Strings) Cut

func (ctx Strings) Cut(s, sep string) (CutResult, error)

Cut slices s around the first instance of sep, returning the text before and after sep. The found result reports whether sep appears in s.

Example:

{{ strings.Cut "apple,banana" "," }} // Output: {apple banana true}
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.Cut "apple,banana" "," }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

{apple banana true}

func (Strings) CutPrefix

func (ctx Strings) CutPrefix(s, sep string) (CutPrefixResult, error)

CutPrefix returns s without the provided leading prefix string and reports whether it found the prefix. If s doesn't start with prefix, CutPrefix returns s, false.

Example:

{{ strings.CutPrefix "Hello, World!" "Hello, " }} // Output: {World! true}
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.CutPrefix "Hello, World!" "Hello, " }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

{World! true}

func (Strings) CutSuffix

func (ctx Strings) CutSuffix(s, sep string) (CutSuffixResult, error)

CutSuffix returns s without the provided ending suffix string and reports whether it found the suffix. If s doesn't end with suffix, CutSuffix returns s, false.

Example:

{{ strings.CutSuffix "Hello, World!" ", World!" }} // Output: {Hello true}
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.CutSuffix "Hello, World!" ", World!" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

{Hello true}

func (Strings) Equal

func (ctx Strings) Equal(s, t string) (bool, error)

Equal reports whether s and t are the same string (case-sensitive).

Example:

{{ strings.Equal "hello" "hello" }} // Output: true
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.Equal "hello" "hello" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

true

func (Strings) EqualFold

func (ctx Strings) EqualFold(s, t string) (bool, error)

EqualFold reports whether s and t are equal under Unicode case-folding, which is a more general form of case-insensitivity.

Example:

{{ strings.EqualFold "Go" "go" }} // Output: true
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.EqualFold "Go" "go" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

true

func (Strings) Fields

func (ctx Strings) Fields(s string) ([]string, error)

Fields splits the string s around each instance of one or more consecutive white space characters, returning a slice of substrings of s or an empty slice if s contains only white space.

Example:

{{ strings.Fields "  hello   world  " }} // Output: [hello world]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.Fields "  hello   world  " }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[hello world]

func (Strings) HasPrefix

func (ctx Strings) HasPrefix(s, prefix string) (bool, error)

HasPrefix tests whether the string s begins with prefix.

Example:

{{ strings.HasPrefix "Hello, World!" "Hello" }} // Output: true
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.HasPrefix "Hello, World!" "Hello" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

true

func (Strings) HasSuffix

func (ctx Strings) HasSuffix(s, suffix string) (bool, error)

HasSuffix tests whether the string s ends with suffix.

Example:

{{ strings.HasSuffix "Hello, World!" "World!" }} // Output: true
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.HasSuffix "Hello, World!" "World!" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

true

func (Strings) Index

func (ctx Strings) Index(s, substr string) (int, error)

Index returns the index of the first instance of substr in s, or -1 if substr is not present in s.

Example:

{{ strings.Index "hello world" "world" }} // Output: 6
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.Index "hello world" "world" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

6

func (Strings) IndexAny

func (ctx Strings) IndexAny(s1, chars string) (int, error)

IndexAny returns the index of the first instance of any Unicode code point from chars in s, or -1 if no Unicode code point from chars is present in s.

Example:

{{ strings.IndexAny "hello" "aeiou" }} // Output: 1
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.IndexAny "hello" "aeiou" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

1

func (Strings) IndexByte

func (ctx Strings) IndexByte(s string, c byte) (int, error)

IndexByte returns the index of the first instance of the given byte in s, or -1 if c is not present in s.

Example:

{{ strings.IndexByte "hello" 'l' }} // Output: 2
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.IndexByte "hello" 'l' }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

2

func (Strings) IndexRune

func (ctx Strings) IndexRune(s string, c rune) (int, error)

IndexRune returns the index of the first instance of the Unicode code point r, or -1 if rune is not present in s.

Example:

{{ strings.IndexRune "hello" 'e' }} // Output: 1
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.IndexRune "hello" 'e' }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

1

func (Strings) Join

func (ctx Strings) Join(a []string, sep string) (string, error)

Join concatenates the elements of a to create a single string. The separator string sep is placed between elements in the resulting string.

Example:

{{ strings.Join ( slice.NewStrings "hello" "world" ) " " }} // Output: hello world
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.Join ( slice.NewStrings "hello" "world" ) " " }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

hello world

func (Strings) LastIndex

func (ctx Strings) LastIndex(s, substr string) (int, error)

LastIndex returns the index of the last instance of substr in s, or -1 if substr is not present in s.

Example:

{{ strings.LastIndex "hello hello" "hello" }} // Output: 6
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.LastIndex "hello hello" "hello" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

6

func (Strings) LastIndexAny

func (ctx Strings) LastIndexAny(s, substr string) (int, error)

LastIndexAny returns the index of the last instance of any Unicode code point from chars in s, or -1 if no Unicode code point from chars is present in s.

Example:

{{ strings.LastIndexAny "hello" "aeiou" }} // Output: 4
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.LastIndexAny "hello" "aeiou" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

4

func (Strings) LastIndexByte

func (ctx Strings) LastIndexByte(s string, c byte) (int, error)

LastIndexByte returns the index of the last instance of the given byte in s, or -1 if c is not present in s.

Example:

{{ strings.LastIndexByte "hello" 'l' }} // Output: 3
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.LastIndexByte "hello" 'l' }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

3

func (Strings) Repeat

func (ctx Strings) Repeat(s string, count int) (string, error)

Repeat returns a new string consisting of count copies of the string s. It panics if count is negative or if the result of (len(s) * count) overflows.

Example:

{{ strings.Repeat "ha" 3 }} // Output: hahaha
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.Repeat "ha" 3 }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

hahaha

func (Strings) Replace

func (ctx Strings) Replace(s, old, replacement string, n int) (string, error)

Replace returns a copy of the string s with the first n non-overlapping instances of old replaced by new. If old is empty, it matches at the beginning of the string and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune string. If n < 0, there is no limit on the number of replacements.

Example:

{{ strings.Replace "hello world hello" "hello" "hi" 1 }} // Output: hi world hello
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.Replace "hello world hello" "hello" "hi" 1 }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

hi world hello

func (Strings) ReplaceAll

func (ctx Strings) ReplaceAll(s, old, replacement string) (string, error)

ReplaceAll returns a copy of the string s with all non-overlapping instances of old replaced by new. If old is empty, it matches at the beginning of the string and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune string.

Example:

{{ strings.ReplaceAll "hello world hello" "hello" "hi" }} // Output: hi world hi
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.ReplaceAll "hello world hello" "hello" "hi" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

hi world hi

func (Strings) Split

func (ctx Strings) Split(s, sep string) ([]string, error)

Split slices s into all substrings separated by sep and returns a slice of the substrings between those separators. If s does not contain sep and sep is not empty, Split returns a slice of length 1 whose only element is s.

Example:

{{ strings.Split "apple,banana,cherry" "," }} // Output: [apple banana cherry]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.Split "apple,banana,cherry" "," }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[apple banana cherry]

func (Strings) SplitAfter

func (ctx Strings) SplitAfter(s, sep string) ([]string, error)

SplitAfter slices s into all substrings after each instance of sep and returns a slice of those substrings. If s does not contain sep and sep is not empty, SplitAfter returns a slice of length 1 whose only element is s.

Example:

{{ strings.SplitAfter "apple,banana,cherry" "," }} // Output: [apple, banana, cherry]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.SplitAfter "apple,banana,cherry" "," }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[apple, banana, cherry]

func (Strings) SplitAfterN

func (ctx Strings) SplitAfterN(s, sep string, n int) ([]string, error)

SplitAfterN slices s into substrings after each instance of sep and returns a slice of those substrings. The count determines the number of substrings to return: n > 0: at most n substrings; n == 0: the result is nil (zero substrings); n < 0: all substrings.

Example:

{{ strings.SplitAfterN "apple,banana,cherry" "," 2 }} // Output: [apple, banana,cherry]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.SplitAfterN "apple,banana,cherry" "," 2 }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[apple, banana,cherry]

func (Strings) SplitN

func (ctx Strings) SplitN(s, sep string, n int) ([]string, error)

SplitN slices s into substrings separated by sep and returns a slice of the substrings between those separators. The count determines the number of substrings to return n > 0: at most n substrings; n == 0: the result is nil (zero substrings); n < 0: all substrings.

Example:

{{ strings.SplitN "apple,banana,cherry" "," 2 }} // Output: [apple banana,cherry]
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.SplitN "apple,banana,cherry" "," 2 }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

[apple banana,cherry]

func (Strings) ToLower

func (ctx Strings) ToLower(s string) (string, error)

ToLower is a wrapper around strings.ToLower that lowercases the input string.

Example:

{{ strings.ToLower "TEST" }} // Output: test
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.ToLower "TEST" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

test

func (Strings) ToTitle

func (ctx Strings) ToTitle(s string) (string, error)

ToTitle returns a copy of the string s with all Unicode letters mapped to their Unicode title case.

Example:

{{ strings.ToTitle "hello world" }} // Output: HELLO WORLD
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.ToTitle "hello world" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

HELLO WORLD

func (Strings) ToUpper

func (ctx Strings) ToUpper(s string) (string, error)

ToUpper is a wrapper around strings.ToUpper that uppercases the input string.

Example:

{{ strings.ToUpper "test" }} // Output: TEST
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.ToUpper "test" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

TEST

func (Strings) ToValidUTF8

func (ctx Strings) ToValidUTF8(s, replacement string) (string, error)

ToValidUTF8 returns a copy of the string s with each run of invalid UTF-8 byte sequences replaced by the replacement string, which may be empty.

Example:

{{ strings.ToValidUTF8 "Hello\xc5World" "?" }}

func (Strings) Trim

func (ctx Strings) Trim(s, cutset string) (string, error)

Trim returns a slice of the string s with all leading and trailing Unicode code points contained in cutset removed.

Example:

{{ strings.Trim "¡¡¡Hello, Gophers!!!" "!¡" }} // Output: Hello, Gophers
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.Trim "¡¡¡Hello, Gophers!!!" "!¡" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

Hello, Gophers

func (Strings) TrimLeft

func (ctx Strings) TrimLeft(s, cutset string) (string, error)

TrimLeft returns a slice of the string s with all leading Unicode code points contained in cutset removed.

Example:

{{ strings.TrimLeft "¡¡¡Hello, Gophers!!!" "!¡" }} // Output: Hello, Gophers!!!
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.TrimLeft "¡¡¡Hello, Gophers!!!" "!¡" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

Hello, Gophers!!!

func (Strings) TrimPrefix

func (ctx Strings) TrimPrefix(s, prefix string) (string, error)

TrimPrefix returns s without the provided leading prefix string. If s doesn't start with prefix, s is returned unchanged.

Example:

{{ strings.TrimPrefix "Hello, World!" "Hello, " }} // Output: World!
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.TrimPrefix "Hello, World!" "Hello, " }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

World!

func (Strings) TrimRight

func (ctx Strings) TrimRight(s, cutset string) (string, error)

TrimRight returns a slice of the string s, with all trailing Unicode code points contained in cutset removed.

Example:

{{ strings.TrimRight "¡¡¡Hello, Gophers!!!" "!¡" }} // Output: ¡¡¡Hello, Gophers
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.TrimRight "¡¡¡Hello, Gophers!!!" "!¡" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

¡¡¡Hello, Gophers

func (Strings) TrimSpace

func (ctx Strings) TrimSpace(s string) (string, error)

TrimSpace returns a slice of the string s, with all leading and trailing white space removed, as defined by Unicode.

Example:

{{ strings.TrimSpace "  \t\n Hello, Gophers \n\t\r\n" }} // Output: Hello, Gophers
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.TrimSpace "  \t\n Hello, Gophers \n\t\r\n" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

Hello, Gophers

func (Strings) TrimSuffix

func (ctx Strings) TrimSuffix(s, prefix string) (string, error)

TrimSuffix returns s without the provided trailing suffix string. If s doesn't end with suffix, s is returned unchanged.

Example:

{{ strings.TrimSuffix "Hello, World!" ", World!" }} // Output: Hello
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ strings.TrimSuffix "Hello, World!" ", World!" }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

Hello

type Tmpl

type Tmpl rootContext

Tmpl provides enhanced template execution capabilities.

func (Tmpl) Exec

func (ctx Tmpl) Exec(name string, data ...any) (any, error)

Exec executes a named template with the provided data and returns the result as a string.

Example 1:

{{ define "T1" }}Hello {{ . }}{{ end }}
{{ $result := tmpl.Exec "T1" "World" }}
Message: {{ $result }} // Output: Message: Hello World
Example
package main

import (
	"fmt"

	"github.com/Eun/xtemplate"
	"github.com/Eun/xtemplate/funcs"
)

func main() {
	s, _ := xtemplate.QuickExecute(
		`{{ define "T1" }}Hello {{ . }}{{ end }}
{{ $result := tmpl.Exec "T1" "World" }}
Message: {{ $result }}`,
		nil,
		funcs.All,
	)
	fmt.Println(s)
}
Output:

Message: Hello World

type URL

type URL rootContext

URL provides access to functions in the url package.

func (URL) JoinPath

func (ctx URL) JoinPath(base string, elem ...string) (string, error)

JoinPath returns a URL string with the provided path elements joined to the existing path of base and the resulting path cleaned of any ./ or ../ elements. Any sequences of multiple slashes will be reduced to a single slash.

Example:

{{ url.JoinPath "https://example.com/foo" "bar" "baz" }}

func (URL) PathEscape

func (ctx URL) PathEscape(s string) (string, error)

PathEscape escapes the string so it can be safely placed inside a URL path segment, replacing special characters (including /) with %XX sequences as needed.

Example:

{{ url.PathEscape "hello world" }}

func (URL) PathUnescape

func (ctx URL) PathUnescape(s string) (string, error)

PathUnescape does the inverse transformation of PathEscape, converting each 3-byte encoded substring of the form "%AB" into the hex-decoded byte 0xAB.

Example:

{{ url.PathUnescape "hello%20world" }}

func (URL) QueryEscape

func (ctx URL) QueryEscape(s string) (string, error)

QueryEscape escapes the string so it can be safely placed inside a URL query. It is identical to PathEscape except that it also escapes '?'.

Example:

{{ url.QueryEscape "hello world?" }}

func (URL) QueryUnescape

func (ctx URL) QueryUnescape(s string) (string, error)

QueryUnescape does the inverse transformation of QueryEscape, converting each 3-byte encoded substring of the form "%AB" into the hex-decoded byte 0xAB.

Example:

{{ url.QueryUnescape "hello%20world%3F" }}

Directories

Path Synopsis
Package funcs package holds function identifiers and collections that can be used with the xtemplate package to specify allowed functions in templates.
Package funcs package holds function identifiers and collections that can be used with the xtemplate package to specify allowed functions in templates.

Jump to

Keyboard shortcuts

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