Skip to content
CodeShellDevPublic

About

CLI program for templating files with the help of Go templates

Topics

Resources

Stars

2 stars

Watchers

1 watching

Forks

Latest commit

 

History

447 Commits

Folders and files

Repository files navigation

Goplater Logo

Goplater

Go templates with superpowers

Read files, call APIs, parse JSON, YAML and Markdown and write your own template functions

See it in action

TEMPLATE.md

+{{- $app := jsonDecode (readRaw "./package.json") -}}

# +{{ upper (index $app "name") }}

Version: +{{ index $app "version" }}

+{{ read "./install.md" }}
goplater template TEMPLATE.md -o README.md

README.md

# MY-APP

Version: 1.2.3

## Install

Run `npm install my-app`

This very README is generated with Goplater.

Contents

Need help? Come join our Matrix Server!

Why Goplater?

  • Familiar. It is Go's text/template syntax. If you know it, you already know Goplater.
  • Batteries included. Read and write files, fetch URLs, work with JSON, YAML, HTML and Markdown, run regex and string operations. See the Standard Library.
  • Write your own functions, inside the template. Define them with define, call them with call. Arguments and return values included.
  • Share and import functions. Put your functions in a file, import them from disk or from a URL and reuse them everywhere.
  • Not just a CLI. The engine behind it, gplt-engine, is a separate library you can embed in your own Go program.
  • Modular. The library is split into independent modules. Load only what you need. Or let the CLI load them all.
  • Automated. Use the GitHub Action and Bot to render templates and automate pull requests. See Automation.

Getting Started

Install with Go:

go install github.com/codeshelldev/goplater@latest

Or download the latest binary from the Releases page, make it executable with chmod +x goplater and run it.

Template your first file:

goplater template examples/app-readme/template.md -o README.md

This creates README.md in your current working directory.

Usage

Templating files

Goplater uses Go's built-in templating library, with actions written as +{{ ... }}. Files that already contain plain {{ }} (Helm charts, GitHub Actions, Mustache) pass through untouched.

File Content: +{{ read "./myfile.txt" }}

Whole folders

Point Goplater at a directory and it mirrors the structure into the output:

goplater template ./examples -o ./out -r

Useful flags:

Flag What it does
-o Output file or directory
-s Source directory for ~/ paths
-r Walk directories
--match Only template files matching a regex
--flatten Drop the directory structure
--root Choose the root that output paths are relative to
--allowed-outputs Limit where templates may write
--trim-max-blank-lines Experimental: Remove blank lines left behind by non-output actions
--dry-run Show what would be written, change nothing
--ignore-errors Continue processing when errors occur

Your own functions

Define a function in the template and call it:

+{{ define "greet(name)" }}
    +{{ returnNext (printf "Hello, %s!" .name) }}
+{{ end }}

+{{ call "greet" "Gopher" }}

Output:

Hello, Gopher!

Prefer Go? Register custom Go functions as well.

Share functions

Keep your functions in one file and import them from the filesystem or from a URL:

+{{ import "funcs" "https://raw.githubusercontent.com/CodeShellDev/goplater/refs/heads/main/examples/funcs" }}
+{{ call "funcs.greet" "John" }}

Pin remote imports to a tag or a commit and treat them like any other dependency: imported functions run inside your template.

Use the engine instead

gplt-engine is not tied to the CLI. Load the modules you want and embed templating in your own Go application. Browse the packages on pkg.go.dev.

Automate with GitHub Actions

Use Goplater in your CI/CD workflows to generate files automatically.

  • Goplater GitHub Action: render templates directly in your GitHub Actions workflows.
  • Goplater Bot: automate file generation in a repository and have the results submitted as a pull request or pushed as a commit.

We use Goplater Bot as well, check him out PR #20!

Standard Library

gplt-engine includes a large and growing selection of built-in functions for use in your templates. Every module is independent, load all of them or only the ones you need.

Goplater ships with all implemented modules in addition to fs-specific and cli dependent functions.

Module Use it for
fs Reading, writing and walking files and directories
outputto Choosing the output path from inside a template
strings, regex Trimming, splitting, replacing, matching
json, yaml Decoding and encoding structured data
html, markdown Querying and editing documents
http Fetching remote resources
math Operators and number helpers
container Maps and slices
base64, conversion Encoding and type conversion
import, return, globals Sharing functions and passing values around
debug Printing while you develop

Need something that is not there? Add your own with a custom module or your own Goplater function file and share it.

read(path string) (string, throws error)

Reads and templates file.

Examples

Example:

+{{ read "/path/to/file" }}

readRaw(path string) (string, throws error)

Reads file (without templating).

Examples

Example:

+{{ readRaw "/path/to/file" }}

readArgs(path string, args any) (string, throws error)

Reads file and passes arguments to it. Arguments are available as .arg in the file being read.

Examples

Example:

+{{ readArgs "/path/to/file" (sliceCreate "my" "args") }}

write(path string, content string) throws error

Writes to a file path.

Examples

Example:

+{{ write "/path/to/file" "Hello" }}

mkdir(path string) throws error

Creates directory at path.

Examples

Example:

+{{ mkdir "/path/to/somewhere/" }}

appendFile(path string, content string) throws error

Appends to an existing file.

Examples

Example:

+{{ appendFile "/path/to/somewhere/" "Goodbye" }}

fsExists(path string) bool

Returns if a file or folder exists at a given path.

Examples

Example:

+{{ if (fsExists "/path/to/somewhere") }}
Path exists!
+{{ end }}

isFile(path string) bool

Returns if a file exists at a given path.

Examples

Example:

+{{ if (isFile "/path/to/file") }}
Path is a file!
+{{ end }}

isDir(path string) bool

Returns if a folder exists at a given path.

Examples

Example:

+{{ if (isDir "/path/to/somewhere") }}
Path is a folder!
+{{ end }}

listDir(path string) ([]string, throws error)

Returns all files and folders inside of a given directory.

Examples

Example:

+{{ join ", " (listDir "/path/to") }}

Output:

/path/to/file1.txt, /path/to/file2.txt, /path/to/folder

walkDir(path string) ([]string, throws error)

Returns all files and folders recursively under a given directory.

Examples

Example:

+{{ join ", " (walkDir "/path/to") }}

Output:

/path/to/file1.txt, /path/to/file2.txt, /path/to/folder, /path/to/folder/file3.txt

fsRemove(path string) throws error

Removes a file or folder at a given path.

Examples

Example:

+{{ fsRemove "/path/to/file/or/folder" }}

joinPath(paths []string) string

Joins paths together.

basePath(path string) string

Returns the last element of a path.

pathDir(path string) string

Returns all but the last element of a path.

fileExt(path string) string

Returns the file name extension of a file path.

absPath(path string) (string, throws error)

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

relPath(basePath string, targetPath string) (string, throws error)

Returns a relative path that is lexically equivalent to targetPath when joined to basePath with an intervening separator. The returned path will always be relative to basePath, even if basePath and targetPath share no elements.

outputTo(path string) throws error

Changes the output path for the current file. Errors if path is not allowed.

globalSet(key string, value any) throws error

Defines a global value with a key.

globalGet(key string) (any, throws error)

Tries to retrieve a global value with a key.

globalHas(key string) bool

Returns whether a given global variable exists.

import(alias string?, path string) throws error

Tries to import a template file with func definitions. Optionally supply an alias for easier access. The fs resolver is only available as an internal module and does not ship with the pkg/gplt/modules directory.

Examples

Example:

+{{ import "https://domain.com/functions" }}

Output:

+{{ call "functions.greet" "John" }}

Example:

+{{ import "funcs" "https://domain.com/functions" }}

Output:

+{{ call "funcs.greet" "John" }}

importExact(alias string?, path string, hash string?) throws error

Same import, but only imports if content matches expected SHA-256 hash.

Examples

Example:

+{{ importExact "funcs" "https://domain.com/functions" "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" }}

Output:

+{{ call "funcs.greet" "John" }}

return(i int, value any) throws error

Sets an output value at the given index.

returnNext(value any) throws error

Appends a value to the output.

returnAll(value []any) throws error

Sets the output object as a whole.

Examples

Example:

+{{ returnAll "1" "2" "3" }}
+{{ returnAll (sliceCreate "1" "2" "3") }}

getOutputs() []any

Returns current outputs.

htmlDecode(html string) (*goquery.Document, throws error)

Decodes html into a document.

htmlDocFindAll(doc *goquery.Document, selector string) ([]*goquery.Selection, throws error)

Finds elements in document by selector (using goquery.Find).

htmlDocFind(doc *goquery.Document, selector string) (*goquery.Selection, throws error)

Finds element in document by selector (using goquery.Find).

htmlFindAll(doc *goquery.Document, selector string) ([]*goquery.Selection, throws error)

Finds elements in element by selector (using goquery.Find).

htmlFind(doc *goquery.Document, selector string) (*goquery.Selection, throws error)

Finds element in element by selector (using goquery.Find).

htmlText(el *goquery.Selection) string

Returns the elements text content.

htmlAttr(el *goquery.Selection, attr string) string

Returns an elements attribute content.

htmlInner(el *goquery.Selection) string

Returns the elements inner html.

markdownDecode(md string) *Document

Decodes markdown into a document.

markdownEncode(doc *Document) string

Encodes a document into markdown.

markdownFindAll(target Searchable, selector string) []*Node

Finds elements in target by selector (using custom).

markdownFind(target Searchable, selector string) *Node

Finds element in target by selector (using custom).

markdownIs(node *Node, selector string) bool

Returns whether node matches selector (using custom).

markdownHTML(doc *Document) (string, throws error)

Returns html markdown representation.

markdownText(node *Node) string

Returns all raw markdown text in a node recursively.

markdownHeadings(doc *Document) []*Heading

Returns all markdown headings.

markdownLinks(doc *Document) []*Link

Returns all markdown links.

markdownLinkURL(link *Link) string

Returns the url of a markdown link node.

markdownLinkSetURL(link *Link, url string)

Sets a link node's url.

markdownLinkSetTitle(link *Link, title string)

Sets a link node's title.

markdownLinkText(link *Link) string

Returns the text of a markdown link node.

markdownImages(doc *Document) []*Image

Returns all markdown images.

markdownImageURL(image *Image) string

Returns the url of a markdown image node.

markdownImageSetURL(image *Image, url string)

Sets a image node's url.

markdownImageSetAlt(image *Image, alt string)

Sets a image node's alt.

markdownParagraphs(doc *Document) []*Paragraph

Returns all markdown paragraphs.

markdownCodeBlocks(doc *Document) []*CodeBlock

Returns all markdown code blocks.

markdownBlockquotes(doc *Document) []*Blockquote

Returns all markdown block quotes.

markdownRemove(node *Node)

Removes a markdown node.

markdownAppend(doc *Document, str string)

Appends text to a markdown document.

markdownPrepend(doc *Document, str string)

Prepends text to a markdown document.

yamlEncode(obj any) (string, throws error)

Encodes an object into a yaml string.

yamlDecode(yaml string) (any, throws error)

Decodes a yaml string into an object.

delete(container map[any]any|[]any, key any) (any, throws error)

Deletes a container entry with the given key.

Examples

Example:

+{{ $newSlice := delete (sliceCreate "Apple" "Banana") 0 }}
+{{ echo $newSlice }}

Output:

[Banana]

set(container map[any]any|[]any, key any, value any) (any, throws error)

Set a container entry value with the given key.

Examples

Example:

+{{ $newSlice := set (sliceCreate "Apple" "Banana") 0 "Strawberry" }}
+{{ echo $newSlice }}

Output:

[Strawberry Banana]

has(container map[any]any|[]any, key any) (bool, throws error)

Returns if an entry with the given key exists in container.

Examples

Example:

+{{ if (has (mapCreate "version" "v1") "version") }}
Container has "version"!
+{{ end }}

slicePush(container []any, value any) []any

Appends a value to a slice.

Examples

Example:

+{{ $newSlice := sliceCreate "Apple" "Banana" }}
+{{ $newSlice = slicePush $newSlice "Strawberry" }}
+{{ echo $newSlice }}

Output:

[Apple Banana Strawberry]

sliceCreate(values []any) []any

Creates a new slice, optionally with values.

Examples

Example:

+{{ $newSlice := sliceCreate "Apple" "Banana" }}
+{{ echo $newSlice }}

Output:

[Apple Banana]

mapCreate(entries []any) (map[string]any, errors)

Creates a new map, optionally with key value pairs. Pairs are constructed one by one, a key followed by the given value. Currently only supports string keys!

Examples

Example:

+{{ $newMap := mapCreate "key1" "value1" "key2" "value2" }}
+{{ echo $newMap }}

Output:

map[key1:value1 key2:value2]

toString(value any) string

Returns a given value as string (using fmt.Sprint, bytes are handled separately).

toBytes(str string) []byte

Turns a string into bytes.

toInt(str string) (int, throws error)

Attempts to parse a string as int.

toFloat64(str string) (float64, throws error)

Attempts to parse a string as float64.

toFloat32(str string) (float32, throws error)

Attempts to parse a string as float32.

toBool(str string) (bool, throws error)

Attempts to parse a string as a bool (using strconv.ParseBool).

echo(data []any)

Outputs data to stdout.

base64Encode(str string) string

Encodes strings with base64.

base64Decode(str string) (string, throws error)

Decodes a base64 string.

hexEncode(str string) string

Encodes a string as hex.

hexDecode(str string) (string, throws error)

Decodes a string as hex.

hash(str string)

Hashes a given string with SHA-256.

sha1(str string)

Hashes a given string with SHA-1.

sha512(str string)

Hashes a given string with SHA-512.

md5(str string)

Hashes a given string with MD-5.

fetch(url string) (string, throws error)

Fetches a resource from a given url. Outputs errors as string.

jsonEncode(obj any) (string, throws error)

Encodes an object into a json string.

jsonDecode(json string) (any, throws error)

Decodes a json string into an object.

abs(numbers int|float64) (int|float64, throws error)

Returns the abs value of a number.

min(a int|float64, b int|float64) (int|float64, throws error)

Returns the smaller value of two numbers.

max(a int|float64, b int|float64) (int|float64, throws error)

Returns the bigger value of two numbers.

clamp(value int|float64, min int|float64, max int|float64) (int|float64, throws error)

Clamps a value between a minimum and maximum value.

pow(base int|float64, exponent int|float64) (float64, throws error)

Performs pow on base with exponent.

sqrt(number int|float64) (float64, throws error)

Returns the square root of a number.

round(number int|float64) (int, throws error)

Rounds a number to the nearest integer.

floor(number int|float64) (int, throws error)

Returns the greatest integer value less than or equal to number.

ceil(number int|float64) (int, throws error)

Returns the least integer value greater than or equal to number.

add(numbers [](int|float64)) (int|float64, throws error)

Adds numbers together.

sub(numbers [](int|float64)) (int|float64, throws error)

Subtracts numbers from each other.

mult(numbers [](int|float64)) (int|float64, throws error)

Multiplies numbers together.

divd(numbers [](int|float64)) (int|float64, throws error)

Divides numbers from each other.

mod(numbers [](int|float64)) (int|float64, throws error)

Performs modulo on numbers.

regexMatch(regex string) (bool, throws error)

Returns whether a string matches the given regex pattern.

regexFind(regex string) ([]string, throws error)

Returns all matches against the given regex pattern in a string.

regexFindGroups(regex string) ([][]string, throws error)

Returns all matches and submatches from the given regex pattern in a string.

regexFindGroupsIndex(regex string) ([][]int, throws error)

Returns all match and submatch positions from the given regex pattern in a string.

regexReplace(regex string) (string, throws error)

Replaces all matches from the given regex pattern in a string with the replaceWith param (which allows using '$1', etc.).

trimSpace(str string) string

Trims space from a string (leading and trailing).

trim(str string, cutset string) string

Trims all chars defined in the cutset param from a string (leading and trailing).

upper(str string) string

Uppercases a string.

lower(str string) string

Lowercases a string.

contains(str string, sub string) bool

Returns whether a string contains the given substring.

count(str string, sub string) int

Counts all occurences of a substring in the given string.

startsWith(str string, prefix string) bool

Returns whether a string starts with the given prefix.

endsWith(str string, suffix string) bool

Returns whether a string ends with the given suffix.

isEmpty(str string) bool

Returns whether the given string is empty.

replace(str string, sub string, replaceWith string) string

Replaces all occurences of a substring in the given string with the replaceWith param.

split(str string, sep string) []string

Split a string by the given seperator.

after(str string, sub string) string

Returns the string after the given substring in a string.

afterLast(str string, sub string) string

Returns the string after the last occurrence of the given substring.

before(str string, sub string) string

Returns the string before the given substring in a string.

beforeLast(str string, sub string) string

Returns the string before the last occurrence of the given substring.

between(str string, startSub string, endSub string) string

Returns the substring between the start and end substring.

cutPrefix(str string, sub string) string

Removes a substring at the start of the given string.

cutSuffix(str string, sub string) string

Removes a substring at the end of the given string.

slice(str string, start int, end int) string

Slices a string based on start and end index.

join(sep string, strings []string) string

Joins multiple strings together by the given separator.

repeat(str string, count int) string

Repeat a string n times.

Contributing

Found a bug or just want to change or add something? Feel free to open up an issue or a PR!

Support

Like this Project? Or just want to help? Why not ⭐️ this Repo? :)

License

This Project is licensed under the MIT License.

Legal

Logo designed by @CodeShellDev — All Rights Reserved.

Go gopher mascot originally created by Renée French, used under the CC BY 4.0 license.

About

CLI program for templating files with the help of Go templates

Topics

Resources

Stars

2 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages