
Introduction
Diecast is a web server that allows you to render a directory tree of template files into HTML, CSS or anything other text-based media in real-time. You can used Diecast to retrieve data from remote sources during the template rendering process, creating dynamic web pages built by consuming APIs and remote files without the need to use client-side Javascript/AJAX calls or an intermediate server framework.
Benefits and Useful Features
Diecast is a good choice for any web project that consumes data from a remote data source for the purpose of building web pages or other text-based file types. Think of Diecast as an intermediary that takes raw data and transforms it, in real-time, into websites.
One of the benefits to this approach is that it enforces separation between data storage and data presentation. It is often the case that web programming frameworks try to “do it all”, they provide access to data, mediate requests, and generate HTML content. It is easy to create close dependencies between these separate tasks, the kind that can be very hard to change or remove.
Diecast, on the other hand, consumes data primarily via HTTP/RESTful API services. This means that the service(s) responsible for providing the data can focus on doing that one thing well, while the parts of the application responsible for turning that data into something visual and interactive can focus on doing that. If you need to change out backend languages in the future, or incorporate new data sources, you can do so without a major overhaul of the frontend components. The HTTP protocol is language-agnostic.
Getting Started
Building a site using Diecast is as easy as putting files in a folder. When you run the diecast
command in this folder (the working directory), Diecast will make the contents of the folder available as a web page (by default, at http://localhost:28419
.) Any file ending in .html
will be treated as a template and be processed before being returned to the user. If no other filenames or paths are requested, Diecast will look for and attempt to serve the file index.html
.
Installation
TODO: make this section much more detailed.
GO111MODULE=on go get github.com/ghetzel/diecast/cmd/diecast
URL Structure
Diecast does not have a concept of URL path routing, but rather strives to enforce simple, linear hierarchies by exposing the working directory directly as routable paths. For example, if a user visits the path /users/list
, Diecast will look for files to serve in the following order:
./users/list/index.html
./users/list.html
./_errors/404.html
./_errors/4xx.html
./_errors/default.html
The first matching file from the list above will be served.
Configuration
You can configure Diecast by creating a file called diecast.yml
in the same folder that the diecast
command is run in, or by specifying the path to the file with the --config
command line option. You can use this configuration file to control how Diecast renders templates and when, as well as set options for how files are accessed and from where. Diecast tries to use “sane defaults” whenever possible, but you can configure Diecast in many ways to suit your needs. For more details on these defaults and to see what goes in a diecast.yml
file, see the Example Config File.
Templating
Beyond merely acting as a simple file server, Diecast comes with a rich templating environment that you can use to build complex sites in a straightforward, easy to understand way. Templates are just files that you tell Diecast to treat specially. The default templating language used by Diecast is Golang’s built-in text/template
package.. Templates files consist of the template content, and optionally a header section called front matter. These headers are used to specify template-specific data such as predefined data structures, paths of other templates to include, rendering options, and the inclusion of remote data via data bindings. An example template looks like this:
---
layout: mobile-v1
bindings:
- name: members
resource: /api/members.json
postprocessors:
- trim-empty-lines
- prettify-html
---
<!DOCTYPE html>
<html>
<body>
<ul>
{{ range $member := $.bindings.members }}
<li>{{ $member }}</li>
{{ end }}
</ul>
</body>
</html>
Language Overview
Golang’s text/template
package provides a fast templating language that is used to generate things like HTML on-the-fly. When generating HTML, CSS, or Javascript documents, Diecast understands that it is working with these languages and performs automatic escaping of code to ensure the output is safe against many common code injection techniques. This is especially useful when using templates to render user-defined input that may contain HTML tags or embedded Javascript.
Intro to text/template
The built-in templating language will be familiar to those coming from a background in other templating languages like Jekyll, Jinja2, and Mustache. Below is a quick guide on how to accomplish certain common tasks when writing templates for Diecast. For detailed information, check out the Golang text/template
Language Overview.
Output Text
Hello {{ $name }}! Today is {{ $date }}.
Conditionals (if/else if/else)
{{ if $pending }}
Access Pending
{{ else if $allowed }}
Access Granted
{{ else }}
Access Denied
{{ end }}
Loops
<h2>Members:</h2>
<ul>
{{ range $name := $names }}
<li>{{ $name }}</li>
{{ end }}
</ul>
<h2>Ranks:</h2>
<ul>
{{ range $i, $name := $rankedNames }}
<li>{{ $i }}: {{ $name }}</li>
{{ end }}
</ul>
Functions
Today is {{ now "ymd" }}, at {{ now "timer" }}.
There are {{ count $names }} members.
Layouts
In addition to rendering individual files as standalone pages, Diecast also supports layouts. Layouts serve as wrapper templates for the files being rendered in a directory tree. Their primary purpose is to eliminate copying and boilerplate code. Layouts are stored in a top-level directory called _layouts
. If the layout _layouts/default.html
is present, it will automatically be used by default (e.g.: without explicitly specifying it in the Front Matter) on all pages. The layout for any page can be specified in the layout
Front Matter property, and the special value layout: none
will disable layouts entirely for that page.
Page Object
Diecast defines a global data structure in the $.page
variable that can be used to provide site-wide values to templates. You can define the page
structure in multiple places, which lets you explicitly provide data when serving templates that doesn’t come from a data binding. The page
structure is inherited by child templates, and all values are merged together to form a single data structure. For example, given the following files:
# diecast.yml
header:
page:
site_title: WELCOME TO MY WEBSITE
---
# _layouts/default.html
page:
colors:
- red
- green
- blue
---
<html>
<head>
<title>{{ if $.page.title }}{{ $.page.title }} :: {{ end }}{{ $.page.site_title }}</title>
</head>
<body>
{{ template "content" . }}
</body>
</html>
---
# index.html
page:
title: Home
---
<h1>Hello World!</h1>
<ul>
{{ range $color := $.page.colors }}
<li style="color: {{ $color }}">{{ $color }}</li>
{{ end }}
</ul>
The final page
data structure would look like this immediately before processing index.html
:
page:
site_title: WELCOME TO MY WEBSITE
colors:
- red
- green
- blue
title: Home
…and the rendered output for index.html
would look like this:
<html>
<head>
<title>Home :: WELCOME TO MY WEBSITE</title>
</head>
<body>
<h1>Hello World!</h1>
<ul>
<li style="color: red">red</li>
<li style="color: green">green</li>
<li style="color: blue">blue</li>
</ul>
</body>
</html>
Conditional Template Loading (Switches)
Diecast templates have a feature that allows you to conditionally switch to loading different templates based on conditions you specify. This is extremely useful for things like loading a different homepage for logged-in users vs. logged out ones.
switch:
- condition: '{{ not (isEmpty $.bindings.current_user) }}'
use: "/logged-in-homepage.html"
- use: "/logged-out-homepage.html"
Switch Types
Switch conditions can perform various checks, which interpret the condition
value differently depending on the check type.
Value of type |
What condition should be |
---|---|
"" or "expression" |
A valid template expression that yields a true value |
"qs:name_of_query_string" |
A string value for the querystring name_of_query_string |
"header:x-my-header" |
A string value for the header x-my-header / X-My-Header |
Data Bindings
Data Bindings (or just bindings) are one of the most important concepts in Diecast. Bindings are directives you add to the Front Matter of layouts and templates that specify remote URLs to retrieve (via an HTTP client built in to diecast
), as well as how to handle parsing the response data and what to do about errors. This concept is extremely powerful, in that it allows you to create complex data-driven sites easily and cleanly by treating remote data from RESTful APIs and other sources as first-class citizens in the templating language.
Overview
Bindings are specified in the bindings
array in the Front Matter of layouts and template files. Here is a basic example that will perform an HTTP GET against a URL, parse the output, and store the parsed results in a variable that can be used anywhere inside the template.
---
bindings:
- name: todos
resource: https://jsonplaceholder.typicode.com/todos/
---
<h1>TODO List</h1>
<ul>
{{ range $todo := $.bindings.todos }}
<li
{{ if $todo.completed }}
style="text-decoration: line-through;"
{{ end }}
>
{{ $todo.title }}
</li>
{{ end }}
</ul>
Controlling the Request
The name
and resource
properties are required for a binding to run, but there are many other optional values supported that allow you to control how the request is performed, how the response if parsed (if at all), as well as what to do if an error occurs (e.g.: connection errors, timeouts, non-2xx HTTP statuses). These properties are as follows:
Property Name | Acceptable Values | Default | Description |
---|---|---|---|
name |
String | - | The name of the variable (under $.bindings ) where the binding’s data is stored. |
resource |
String | - | The URL to retrieve. This can be a complete URL (e.g.: “https://…”) or a relative path. If a path is specified, the value [bindingPrefix] will be prepended to the path before making the request. |
body |
Object | - | An object that will be encoded according to the value of formatter and used as the request body. |
except |
[]String | - | If set, and the request path matches any of the paths/path globs herein, the binding will not evaluate and be marked optional. |
fallback |
Anything | - | If the binding is optional and returns a non-2xx status, this value will be used instead of null . |
formatter |
json, form |
json |
Specify how the body should be serialized before performing the request. |
headers |
Object | - | An object container HTTP request headers to be included in the request. |
if_status |
Anything | - | Actions to take when specific HTTP response codes are encountered. |
insecure |
Boolean | false |
Whether SSL/TLS peer verification should be enforced. |
method |
String | get |
The HTTP method to use when making the request. |
no_template |
Boolean | false |
If true, inline expressions in binding values will not be honored. |
not_if |
String | - | If this value or expression yields a truthy value, the binding will not be evaluated. |
on_error |
String | - | What to do if the request fails. |
only |
[]String | - | If set, and the request path does not match any of the paths/path globs herein, the binding will not evaluate and be marked optional. |
only_if |
String | - | Only evaluate if this value or expression yields a truthy value. |
optional |
Boolean | false |
Whether a response error causes the entire template render to fail. |
paginate |
[Paginate Config])(#pagination) | - | Paginates through a resultset by performing the binding request repeatedly until an edge condition is met, then returns all the results. |
param_joiner |
String | ; |
When a key in params is specified as an array, how should those array elements be joined into a single string value. |
params |
Object | - | An object representing the query string parameters to append to the URL in resource . Keys may be any scalar value or array of scalar values. |
parser |
json, html, text, raw |
json |
Specify how the response body should be parsed into the binding variable. |
rawbody |
String | - | The exact string to send as the request body. |
skip_inherit_headers |
Boolean | false |
If true, no headers from the originating request to render the template will be included in this request, even if Header Passthrough is enabled. |
transform |
String | - | A JSONPath expression used to transform the resource response before putting it in $.bindings . |
Handling Response Codes and Errors
By default, the response to a binding’s HTTP request must be a 200-series HTTP status code. If it is not (e.g. returns an 404 or 500 error), Diecast will return an error page instead. Custom error pages live in a top-level _errors
folder. This folder will be checked for specially-named files that are to be used for handling different error types. These filenames will be checked, in order, in the event of a binding error:
/_errors/404.html
Uses the exact HTTP status code that was encountered. Use this to handle specific, well-known error cases like “404 Not Found” or “500 Internal Server Error”.
/_errors/4xx.html
Specifies an error page that is used for an entire range of error types. HTTP errors are grouped by type; e.g.: status codes between 400-499 indiciate a client error that the user can fix, whereas 500-599 describes server errors the user cannot do anything about.
/_errors/default.html
Specifies an error page that is used to handle any non-2xx HTTP status, as well as deeper problems like connection issues, SSL security violations, and DNS lookup problems.
Conditional Evaluation
By default, all bindings specified in a template are evaluated in the order they appear. It is sometimes useful to place conditions on whether a binding will evaluate. You can specify these conditions using the only_if
and not_if
properties on a binding. These properties take a string containing an inline template. If the template in an only_if
property returns a “truthy” value (non-empty, non-zero, or “true”), that binding will be run. Otherwise, it will be skipped. The inverse is true for not_if
: if truthy, the binding is not evaluated.
---
bindings:
# --------------------------------------------------------------------------------
# Always evaluated
- name: always
resource: /api/status
# --------------------------------------------------------------------------------
# Only evaluated if the "login" query string is a "truthy" values (i.e.: "1",
# "true", "yes")
- name: user
resource: /api/users/self
only_if: '{{ qs "login" }}'
# --------------------------------------------------------------------------------
# Evaluated every day except Mondays
- name: i_hate_mondays
resource: /api/details
not_if: '{{ eqx (now "day") "Monday" }}'
---
Repeaters
TODO
Pagination
A binding can be configured to perform its request repeatedly, modifying the binding with data from the previous request, allowing for various API pagination access patterns to be accessed under a single binding.
---
bindings:
- name: pages
resource: http://elasticsearch:9200/my_search_index/_search
params:
q: 'type:customer'
paginate:
total: '{{ $.hits.total }}' # "total number of results overall"
count: '{{ count $.hits.hits }}' # "number of results on this page"
done: '{{ eqx (count $.hits.hits) 0 }}' # this should evaluate to a truthy value when we're out hits
max: 10000 # a hard cap on the number of results so we don't paginate forever
data: '$.hits.hits' # a JSONPath query that will transform the data before putting it in the "data" key in the response
params:
size: '{{ qs "limit" 100 }}' # set the ?size querystring
from: '{{ $.page.counter }}' # set the ?from querystring to the running results counter
---
JSONPath Expressions
Bindings support a flexible mechanism for transforming response data as read from the binding resource. JSONPath is similar to XPath expressions that allow for data to be selected and filtered from objects and arrays.
Postprocessors
Postprocessors are routines that are run after the template is rendered for a request, but before the response is returned to the client. This allows for actions to be taken on the final output, processing it in various ways.
Prettify HTML
The prettify-html
postprocessor will treat the incoming document as HTML, running it through an autoformatter and autoindent routine. This is useful for ensuring that well-formed and visually pleasing HTML is emitted from Diecast.
Trim Empty Lines
The trim-empty-lines
postprocessor removes all lines from the final document that are zero-length or only contain whitespace. This is especially useful when producing responses encoded as Tab-Separated Values (TSV) or Comma-Separated Values (CSV).
Renderers
Diecast supports various methods of converting the output of the rendered templates and layouts into a finished product that can be delivered to the client. Renderers receive the rendered template as input and are responsible for writing something to the client.
HTML
The HTML renderer ensures that external template content, that is, template data sourced from a variable or function, is escaped properly within the context of the type of file being processed (HTML, CSS, or Javascript.) This makes user-defined content safe to use in Diecast because it will always be sanitized before being returned to the client. The html
renderer is the default renderer if no other renderer is specified.
The pdf
renderer is used in tandem with the HTML renderer to convert the HTML page into a PDF document that is then returned to the client.
Sass
The sass
renderer takes file or template output and compiles it on the fly using the libsass
library. This is the default renderer for files matching the pattern *.scss
.
Mounts
Another useful feature of Diecast is its ability to expose multiple, overlapping file trees in one logical namespace. These alternative file trees (called mounts) can be located locally or remotely, and through careful configuration of the scope and order of mounts, fairly complex serving configurations can be achieved.
For example, lets take a GET request to the path /assets/js/my-lib.js
. By default, Diecast will look for this path relative to the working directory, and if the file is not found, will return an error. However, a mount can be configured to handle this path (or its parent folder(s)), serving the file from another directory outside of the working directory, or from another server entirely.
Mounts can also be stacked, in which the URL path they handle refers to multiple possible locations. When multiple mounts are eligible to handle a request, the requested file is passed to each mount in the order they are defined. The first mount to successfully handle the file will do so. This setup can be used to present multiple directories as a single logical one, as well as providing useful fallbacks and proxying capabilities granular to the individual file level.
File
The file mount type is used for mount sources that do not begin with a URL scheme. This means paths like /usr/share/www/
or ./some/other/path
. Consider the following mount configuration:
mounts:
- mount: /usr/share/www/
to: /assets/
A request for the file /assets/js/my-lib.js
would first attempt to find that file at the path /usr/share/www/js/my-lib.js
. Note that the /assets/
part of the URL path was substituted for the value of the mount
key.
HTTP
The HTTP (aka proxy) mount type is used for sources starting with http://
or https://
. In this configuration, the behavior matches that of the File type, except the content is sourced by making an HTTP request to a URL. Consider the following mount configuration:
mounts:
- mount: https://assets.example.com/
to: /assets/
A request for the file /assets/js/my-lib.js
here would result in an HTTP GET request to https://assets.example.com/assets/js/my-lib.js
. If the response is a 2xx-series status code, the response body will be sent to the client as if the file resided on the server itself. Note that in this case, the entire original URL path is sent along to the remote server.
This is useful because it allows Diecast to act as a proxy server, while still layering on features like additional mounts and authenticators. This means Diecast can be configured to proxy a website, but intercept and substitute requests for specific files on a case-by-case basis. For example:
mounts:
- mount: /usr/share/custom-google-logos/
to: /logos/
- mount: https://google.com
to: /
In this configuration, a request to http://localhost:28419/
will load Google’s homepage, but when the browser attempts to load the logo (typically located at /logos/...
), that request will be routed to the local /usr/share/custom-google-logos/
directory. So if the logo for that day is at /logos/doodles/2018/something.png
, and the file /usr/share/custom-google-logos/doodles/2018/something.png
exists, that file will be served in lieu of the version on Google’s servers.
Authenticators
Diecast exposes the capability to add authentication and authorization to your applications through the use of configurable authenticators. These are added to the diecast.yml
configuration file, and provide a very flexible mechanism for protecting parts or all of the application using a variety of backends for verifying users and user access.
Example: Basic HTTP Authentication for the Whole Site
Here is a configuration example that shows how to prompt a client for a username and password when accessing any part of the current site. The permitted users are stored in a standard Apache .htaccess
file, which is consulted every time a requested path matches. If specific path patterns aren’t included or excluded, all paths will be protected.
authenticators:
- type: basic
options:
realm: 'Da Secure Zone'
htpasswd: '/etc/my-app/htpasswd'
Including and Excluding Paths
It is possible to specify specific paths (or wildcard patterns) for which the authenticator must or must not be applicable to.
To specify a specific set of paths, use the path
configuration option:
authenticators:
- type: basic
paths:
- '/very/specific/secret/place'
- `/secure/**`
To specify a set of paths to exclude from authentication, use the exclude
option:
authenticators:
- type: basic
exclude:
- '/assets/**'
Authenticator Types
Several authentication/authorization backends are supported.
type: "basic"
Prompts users for credentials using Basic access HTTP Authentication, a widely-supported authentication mechanism supported by most web browsers and command-line tools.
Supported Options
Option | Description |
---|---|
realm |
The Realm exposed with Basic HTTP Authentication; specifies parts of the site that may share credentials. |
htpasswd |
A server-side file path to an Apache htaccess file that contains valid usernames and password hashes. |
credentials |
Similar to htpasswd , this option is a map that allows you to place username: 'password-hash' pairs directly into the configuration file. |
type: "oauth2"
Allows for third-party authentication providers (Google, Facebook, GitHub, etc.) to be used for authenticating a user session. This authenticator requires the callback
configuration option, which specifies a complete URL that the third-party will send users to upon successful login using their service.
Supported Options
Option | Description |
---|---|
provider |
The name of a built-in OAuth2 provider, or “custom”. Built-in providers include: amazon , facebook , github , gitlab , google , microsoft-live , slack , spotify . |
client_id |
The Client ID provided by your OAuth2 provider. |
secret |
The Client Secret provided by your OAuth2 provider. |
scopes |
A list of named scopes requested from the OAuth2 provider. |
cookie_name |
The name of the session cookie stored in the user’s browser. |
lifetime |
How long the authenticated session will last. |
auth_url |
If provider is “custom”, specifies the OAuth2 authentication URL. |
token_url |
If provider is “custom”, specifies the OAuth2 validation URL. |
Actions
In addition to serving file and processing templates, Diecast also includes support for performing basic server-side actions. These actions are exposed and triggered by a RESTful web API that is implemented in the diecast.yml
configuration file. The data made available through these custom API endpoints is gathered by executing shell commands server-side, and as such comes with certain innate risks that need to be addressed in order to maintain a secure application environment.
WARNING: Danger Zone
Be advised that this feature can very easily be misused or implemented in an insecure way. This feature is intended to provide extremely basic reactive capabilities in an otherwise constrained deployment environment. Diecast will take some measures to sanitize user inputs before inserting them into shell commands, and will not allow the program to even start as the root
user if actions are defined (unless the DIECAST_ALLOW_ROOT_ACTIONS
environment variable is set to “true”). However, none of this is a substitute for strictly controlling the scope and use of this feature.
Some tips for making the most effective use of this feature:
- Use sparingly. The most secure code is the code that is never written.
- Use Authenticators. Protect your action endpoints with some form of authentication.
- Keep it simple. If you find your logic getting too complex or too clever, re-evaluate your needs and approach.
Be careful out there.
Paths and Steps
Actions are defined under the actions
configuration key, and are an array of definitions that specify a URL path that, when requested, will execute a sequence of steps and respond with the resulting output. In this way, data can be retrieved, manipulated, and returned to the user. Below is a very basic example that will return the server’s current time:
actions:
- path: /api/time
method: get
steps:
- type: shell
parser: lines
data: date
The output a user would see if they visit http://localhost:28419/api/time would look like this:
["Tue Jan 02 15:04:05 MST 2006"]
Steps are defined as an array of specific actions, be it executing a shell script, converting output from one format to another, or sorting and filtering data. Steps are designed to be chained together to create composable data processing pipelines.
Step Type shell
The shell step is used to execute a server-side program and return the output. A successful program will run, optionally using the environment variables provided to make use of request-specific details, and print the results to standard output (by default, a JSON-encoded document, but this can be controlled with the parser
option). The program should exit with a status of zero (0) to indicate success, and non-zero to indicate failure. If the program exits with a non-zero status, the standard output is assumed to be a descriptive error.
Shell Environment
Below are the environment variables made available to the shell
step on invocation:
REQ_HEADER_*
: Represents all HTTP headers supplied by the user, prefixed withREQ_HEADER_
, with the header name upper-cased and all non-alphanumeric characters converted to an underscore (_
).REQ_PARAM_*
: Represents all query string parameters on the request URL, also upper-cased and underscore-separated.- Example:
/api/test?is_enabled=true&hello=there
will yield two environment variables: REQ_PARAM_IS_ENABLED=true
REQ_PARAM_HELLO=there
- Example:
REQ_PARAM_*
: Represents positional parameters in the URL, specified in thepath
configuration in the action. For example, ifpath: '/api/actions/:action-name'
, then the script will be called with the environment variableREQ_PARAM_ACTION_NAME
. If both a URL parameter and query string parameter have the same name, the URL parameter will overwrite the query string parameter.
Step Type process
The process step is used to manipulate the output from a previous step in some way. This can be used to convert script output into complex nested data structures, sort lines of text, or perform other operations on the data.
Process Operation
What action to take on input data is specified in the step’s data
option.
Process Operation | Description |
---|---|
sort |
Sort an array of strings lexically ascending order. |
rsort |
Same as sort , but in descending order. |
diffuse |
Takes an array of strings in the format “nested.key.name=value” and converts that into a deeply-nested map (e.g.: {"nested": {"key": {"name": "value"}}} ). Data types for values are automatically detected. |
Examples
Creates an endpoint at [http://localhost:28419/api/deploy] that returns an object containing the current git branch and revision of the Diecast runtime directory:
actions:
- path: /api/deploy
method: get
steps:
- type: shell
data: |
#!/usr/bin/env bash
echo "branch=$(git rev-parse --abbrev-ref HEAD)"
echo "revision=$(git rev-parse HEAD)"
- type: process
data: diffuse
Function Reference
Diecast ships with a potentially-overwhelming number of functions for use in templates, includes, and certain Front Matter fields.
Arrays and Objects
- any
- append
- apply
- coalesce
- compact
- count
- difference
- diffuse
- exceptKeys
- filter
- filterByKey
- filterLines
- findKey
- first
- firstByKey
- flatten
- get
- groupBy
- has
- head
- indexOf
- intersect
- irSortByKey
- irsort
- isLastElement
- isort
- isortByKey
- jsonPath
- keys
- last
- leastcommon
- mapify
- mostcommon
- objectify
- onlyKeys
- page
- pluck
- rSortByKey
- rest
- reverse
- rsort
- set
- shuffle
- shuffleInPlace
- slice
- sliceify
- sort
- sortByKey
- sslice
- stringify
- tail
- transformValues
- uniq
- uniqByKey
- uniqByKeyLast
- values
Arrays and Objects
For converting, modifying, and filtering arrays, objects, and arrays of objects. These functions are especially useful when working with data returned from Bindings.
any
any INPUT [WANTED ...]
Return whether an array contains any of a set of desired items.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
array |
The array to search within. |
WANTED |
any (1+) |
A list of values, any of which being present in the given array will return true. |
Examples
{{ any ["a", "e", "i", "o", "u"] "e" "y" "x" }}
true
{{ any ["r", "s", "t", "l", "n", "e"] "f" "m" "w" "o" }}
false
append
append ARRAY [VALUES ...]
Append one or more values to the given array. If the array given is not in fact an array, it will be converted into one, with the exception of null values, which will create an empty array.
Arguments
Name | Data Type | Description |
---|---|---|
ARRAY |
array |
The array to append items to. |
VALUES |
any (1+) |
One or more items to append to the given array. |
Examples
{{ append ["a", "b"] "c" "d" }}
[ "a", "b", "c", "d" ]
apply
apply INPUT [FUNCTIONS ...]
Apply a function to each of the elements in the given array. Note that functions must be unary (accept one argument of type any).
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
array |
The array to modify. |
FUNCTIONS |
strings (1+) |
One or more functions to pass each element to. Only supports functions that accept a zero or one arguments. |
Examples
{{ apply ["a", "B", "C", "d"] "upper" }}
[ "A", "B", "C", "D" ]
{{ apply ["a", "B", "C", "d"] "upper" "lower" }}
[ "a", "b", "c", "d" ]
coalesce
coalesce INPUT [JOINER ...]
Convert an array of objects or object representing a deeply-nested hierarchy of items and collapse it into a flat (not nested) object.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
array/object |
The array or object to expand into a deeply-nested object. |
JOINER |
string (1+) |
The string used in object keys that separates levels of the hierarchy. |
compact
compact INPUT
Return an copy of given array with all empty, null, and zero elements removed.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
array |
The array to compact. |
Examples
{{ uniq ["a", null, "b", 0, false, "c"] }}
[ "a", "b", "c" ]
count
count INPUT
Identical to the built-in “len” function, but is less picky about types.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
array |
The array to read from. |
Examples
{{ count ["a", "b", "c", "d"] }}
4
difference
difference FIRST SECOND
Return the first array with common elements from the second removed.
Arguments
Name | Data Type | Description |
---|---|---|
FIRST |
array |
The first array. |
SECOND |
array |
The second array. |
Examples
{{ difference ["b", "a", "c"] ["c", "b", "d"] }}
[ "a" ]
{{ difference ["a", "b", "c"] ["x", "y", "z"] }}
[ "a", "b", "c" ]
diffuse
diffuse INPUT [JOINER ...]
Convert an array of objects or object representing a single-level hierarchy of items and expand it into a deeply-nested object.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
array/object |
The array or object to expand into a deeply-nested object. |
JOINER |
string (1+) |
The string used in object keys that separates levels of the hierarchy. |
Examples
{{ diffuse {"properties/enabled": true, "properties/label": "items", "name": "Items", "properties/tasks/0": "do things", "properties/tasks/1": "do stuff"} "/" }}
{ "name": "Items", "properties": { "enabled": true, "label": "items", "tasks": [ "do things", "do stuff" ] } }
exceptKeys
exceptKeys IN [KEYS ...]
Return the given object with the specified keys removed.
Arguments
Name | Data Type | Description |
---|---|---|
IN |
object |
The object to filter. |
KEYS |
string (1+) |
Zero or more keys to exclude from the output. |
Examples
{{ exceptKeys {"a": 1, "b": 2, "c": 3} "a" "c" }}
{ "b": 2 }
filter
filter ARRAY EXPRESSION
Return the given array with only elements where expression evaluates to a truthy value.
Arguments
Name | Data Type | Description |
---|---|---|
ARRAY |
array |
The array to operate on. |
EXPRESSION |
string |
An “{{ expression }}” that will be called on each element. Only if the expression does not yield a zero value (0, false, “”, null) will the element be included in the resulting array. |
Examples
{{ filter [1, 2, 3, 4, 5] "{{ isOdd . }}" }}
[ 1, 3, 5 ]
{{ filter [{"active": true, "a": 1}, {"b": 2}, {"active": true, "c": 3}] "{{ .active }}" }}
[ { "a": 1, "active": true }, { "active": true, "c": 3 } ]
filterByKey
filterByKey ARRAY KEY EXPRESSION
Return a subset of the elements in the given array whose values are objects that contain the given key. Optionally, the values at the key for each object in the array can be passed to a template expression. If that expression produces a truthy value, the object will be included in the output. Otherwise it will not.
Arguments
Name | Data Type | Description |
---|---|---|
ARRAY |
array |
The array of objects to filter. |
KEY |
string |
The name of the key on each object in the given array to check the value of. |
EXPRESSION |
string |
The “{{ expression }}” to apply to the value at key from each object. Uses the same expression rules as filter |
Examples
{{ filterByKey [{"id": "a", "value": 1}, {"id": "b", "value": 1}, {"id": "c", "value": 2}] 1 }}
[ { "id": "a", "value": 1 }, { "id": "b", "value": 1 } ]
filterLines
filterLines ARRAY_OR_STRING REGEXP [NEGATE]
Return a subset of the lines in the given string or array of strings that match the supplied regular expression. Optionally, the match may be negated, which return all lines that do NOT match the regular expression.
Arguments
Name | Data Type | Description |
---|---|---|
ARRAYORSTRING |
array, string |
The string or array of strings to scan. |
REGEXP |
string |
A regular expression used to filter the given input. |
NEGATE |
boolean |
If true, only values that do not match regexp will be returned. |
Examples
{{ filterLines "# Hello\n# Author: Me\necho hello\nexit 1" "^#" }}
[ "# Hello", "# Author: Me" ]
{{ filterLines "# Hello\n# Author: Me\necho hello\nexit 1" "^#" true }}
[ "echo hello", "exit 1" ]
findKey
findKey INPUT KEY
Recursively scans the given array or object and returns all values of the given key.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
array, object |
The object or array of object to retrieve values from. |
KEY |
string |
The name of the key in any objects encountered whose value should be included in the output. |
Examples
{{ findKey [{"id": 1, "children": [{"id": 3}, {"id": 5}, {"id": 8}]} "id" }}
[ 1, 3, 5, 8 ]
first
first INPUT
Return the first value from the given array, or null if the array is empty.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
array |
The array to read from. |
Examples
{{ first ["a", "b", "c", "d"] }}
"a"
firstByKey
firstByKey ARRAY KEY EXPRESSION
Identical to filterByKey, except it returns only the first object in the resulting array instead of the whole array.
Arguments
Name | Data Type | Description |
---|---|---|
ARRAY |
array |
The array of objects to filter. |
KEY |
string |
The name of the key on each object in the given array to check the value of. |
EXPRESSION |
string |
The “{{ expression }}” to apply to the value at key from each object. Uses the same expression rules as filter |
Examples
{{ firstByKey [{"id": "a", "value": 1}, {"id": "b", "value": 1}, {"id": "c", "value": 2}] 1 }}
{ "id": "a", "value": 1 }
flatten
flatten INPUT
Return an array of values with all nested arrays collapsed down to a single, flat array.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
array |
The array to flatten. |
Examples
{{ flatten ["a", ["a", "b"], ["b", "b", ["c"]]] }}
[ "a", "a", "b", "b", "b", "c" ]
get
get OBJECT KEY [FALLBACK]
Retrieve a value from a given object. Key can be specified as a dot.separated.list string or array of keys that describes a path from the given object, through any intermediate nested objects, down to the object containing the desired value.
Arguments
Name | Data Type | Description |
---|---|---|
OBJECT |
object |
The object to retrieve the value from |
KEY |
string, array |
The key name, path, or array of values representing path segments pointing to the value to retrieve. |
FALLBACK |
any |
If the value at the given key does not exist, this value will be returned instead. If not specified, the default return value is null. |
Examples
{{ get {"name: "Bob"} "name" }}
"Bob"
{{ get {"properties": {"info": {"name: "Bob"}}} "properties.info.name" }}
"Bob"
{{ get {"properties": {"info": {"name: "Bob"}}} "properties.info.age" }}
null
{{ get {"properties": {"info": {"name: "Bob"}}} "properties.info.age" 42 }}
42
{{ get {"properties": {"info.name": "Bob"}} ["properties", "info.name"] }}
"Bob"
groupBy
groupBy ARRAY KEY
Return the given array of objects as a grouped object, keyed on the value of the specified group field. The field argument can be an expression that receives the value and returns a transformed version of it.
Arguments
Name | Data Type | Description |
---|---|---|
ARRAY |
array |
An array of objects to group. |
KEY |
string |
The key to retreive from each object, the value of which will determine the group names. |
Examples
{{ groupBy [{"name": "Bob", "title": "Friend"}, {"name": "Mallory", "title": "Foe"}, {"name": "Alice", "title": "Friend"}] "title" }}
{ "Foe": [ { "name": "Mallory", "title": "Foe" } ], "Friend": [ { "name": "Bob", "title": "Friend" }, { "name": "Alice", "title": "Friend" } ] }
has
has WANTED INPUT
Return whether a specific element is in an array.
Arguments
Name | Data Type | Description |
---|---|---|
WANTED |
any |
The value being sought out. |
INPUT |
array |
The array to search within. |
Examples
{{ has "e" ["a", "e", "i", "o", "u"] }}
true
{{ has "y" ["a", "e", "i", "o", "u"] }}
false
{{ has "13" ["3", "5", "8", "13"] }}
true
{{ has 13 ["3", "5", "8", "13"] }}
true
{{ has 14 ["3", "5", "8", "13"] }}
false
head
head INPUT COUNT
Return the first n items from an array.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
array |
The array to read from. |
COUNT |
integer |
The number of items to retrieve from the beginning of the array. |
Examples
{{ head ["a", "b", "c", "d"] 2 }}
[ "a", "b" ]
indexOf
indexOf INPUT WANTED
Iterate through an array and return the index of a given value, or -1 if not present.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
array |
The array to search within. |
WANTED |
any |
The value being sought out. |
Examples
{{ indexOf ["a", "e", "i", "o", "u"] "e" }}
1
{{ indexOf ["a", "e", "i", "o", "u"] "y" }}
-1
intersect
intersect FIRST SECOND
Return the intersection of two arrays.
Arguments
Name | Data Type | Description |
---|---|---|
FIRST |
array |
The first array. |
SECOND |
array |
The second array. |
Examples
{{ intersect ["b", "a", "c"] ["c", "b", "d"] }}
[ "b", "c" ]
{{ intersect ["a", "b", "c"] ["x", "y", "z"] }}
[]
irSortByKey
irSortByKey ARRAY KEY [EXPRESSION]
Same as isortByKey, but reversed (case-insensitive compare).
Arguments
Name | Data Type | Description |
---|---|---|
ARRAY |
array |
The array of objects to sort. |
KEY |
string |
The name of the key on each object whose values should determine the order of the output array. |
EXPRESSION |
string |
The “{{ expression }}” to apply to the value at key from each object before determining uniqueness. Uses the same expression rules as filter |
Examples
{{ irSortByKey [{"name": "Bob"}, {"name": "Mallory"}, {"name": "Alice"}] "name" }}
[ { "name": "Mallory" }, { "name": "Bob" }, { "name": "Alice" } ]
irsort
irsort INPUT
Return the array sorted in lexical descending order (case-insensitive.)
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
array |
The array to sort. |
Examples
{{ irsort ["bob", "ALICE", "Mallory"] }}
[ "Mallory", "bob", "ALICE" ]
isLastElement
isLastElement INDEX ARRAY
Returns whether the given index in the given array is the last element in that array.
Arguments
Name | Data Type | Description |
---|---|---|
INDEX |
integer |
The current index of the item in the collection. |
ARRAY |
array |
The array being checked |
isort
isort INPUT
Return an array sorted in lexical ascending order (case-insensitive.)
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
array |
The array to sort. |
Examples
{{ isort ["bob", "ALICE", "Mallory"] }}
[ "ALICE", "bob", "Mallory" ]
isortByKey
isortByKey ARRAY KEY [EXPRESSION]
Sort the given array of objects by comparing the values of the given key for all objects (case-insensitive compare).
Arguments
Name | Data Type | Description |
---|---|---|
ARRAY |
array |
The array of objects to sort. |
KEY |
string |
The name of the key on each object whose values should determine the order of the output array. |
EXPRESSION |
string |
The “{{ expression }}” to apply to the value at key from each object before determining uniqueness. Uses the same expression rules as filter |
Examples
{{ isortByKey [{"name": "Bob"}, {"name": "Mallory"}, {"name": "Alice"}] "name" }}
[ { "name": "Alice" }, { "name": "Bob" }, { "name": "Mallory" } ]
jsonPath
jsonPath QUERY DATA
Returns the input object filtered using the given JSONPath query.
Arguments
Name | Data Type | Description |
---|---|---|
QUERY |
string |
The JSONPath query to filter by. |
DATA |
object |
The object being filtered. |
keys
keys OBJECT
Return an array of key names specifying all the keys of the given object.
Arguments
Name | Data Type | Description |
---|---|---|
OBJECT |
object |
The object to return the key names from. |
Examples
{{ keys {"id": "a", "value": 1} }}
[ "id", "value" ]
last
last INPUT
Return the last value from the given array, or null if the array is empty.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
array |
The array to read from. |
Examples
{{ last ["a", "b", "c", "d"] }}
"d"
leastcommon
leastcommon INPUT
Return the element in a given array that appears the least frequently.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
array |
The array to read from. |
Examples
{{ leastcommon ["a", "a", "b", "b", "b", "c"] }}
"c"
mapify
mapify
Return the given value returned as a rangeable object.
mostcommon
mostcommon INPUT
Return the element in a given array that appears the most frequently.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
array |
The array to read from. |
Examples
{{ mostcommon ["a", "a", "b", "b", "b", "c"] }}
"b"
objectify
objectify INPUT KEY_FIELD VALUE_FIELD [KEY_VALUE_SEPARATOR]
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
array |
An array of objects or strings to parse and convert into an object |
KEYFIELD |
string |
The name of the field in the parsed input whose value will become the keys in the resultant object. |
VALUEFIELD |
string |
The name of the field in the parsed input whose value will become the values in the resultant object. |
KEYVALUESEPARATOR |
string |
If given an array of strings, the first occurrence of this string will separate the key and value portions of the string. |
Examples
{{ objectify [{"label": "First Name", "value": "firstName"}, {"label": "Last Name", "value": "lastName"}] "value" "label" }}
{ "firstName": "First Name", "lastName": "Last Name" }
{{ objectify ["test=true", "hello=there"] }}
{ "hello": "there", "test": true }
onlyKeys
onlyKeys IN [KEYS ...]
Return the given object with only the specified keys included.
Arguments
Name | Data Type | Description |
---|---|---|
IN |
object |
The object to filter. |
KEYS |
string (1+) |
Zero or more keys to include in the output. |
Examples
{{ onlyKeys {"a": 1, "b": 2, "c": 3} "a" "c" }}
{ "a": 1, "c": 3 }
page
page PAGENUM PERPAGE
Returns an integer representing an offset used for accessing paginated values when given a page number and number of results per page.
Arguments
Name | Data Type | Description |
---|---|---|
PAGENUM |
integer |
The page number to calculate the offset of. |
PERPAGE |
integer |
The maximum number of results that can appear on a single page. |
Examples
{{ page 1 25 }}
0
{{ page 2 25 }}
25
{{ page 3 25 }}
50
{{ page 2 10 }}
10
pluck
pluck ARRAY KEY [ADDITIONAL_KEYS ...]
Retrieve a value at the given key from each object in a given array of objects.
Arguments
Name | Data Type | Description |
---|---|---|
ARRAY |
array |
The array of objects to retrieve values from. |
KEY |
string |
The name of the key on each object whose values should returned. |
ADDITIONAL_KEYS |
strings (1+) |
If specified, the values of these additional keys will be appended (in order) to the output array. |
Examples
{{ pluck [{"name": "Bob"}, {"name": "Mallory"}, {"name": "Alice"}] "name" }}
[ "Bob", "Mallory", "Alice" ]
rSortByKey
rSortByKey ARRAY KEY [EXPRESSION]
Same as sortByKey, but reversed.
Arguments
Name | Data Type | Description |
---|---|---|
ARRAY |
array |
The array of objects to sort. |
KEY |
string |
The name of the key on each object whose values should determine the order of the output array. |
EXPRESSION |
string |
The “{{ expression }}” to apply to the value at key from each object before determining uniqueness. Uses the same expression rules as filter |
Examples
{{ rSortByKey [{"name": "bob"}, {"name": "Mallory"}, {"name": "ALICE"}] "name" }}
[ { "name": "Mallory" }, { "name": "bob" }, { "name": "ALICE" } ]
rest
rest INPUT
Return all but the first value from the given array, or an empty array of the given array’s length is <= 1.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
array |
The array to read from. |
Examples
{{ rest ["a", "b", "c", "d"] }}
[ "b", "c", "d" ]
{{ rest ["a"] }}
[]
reverse
reverse ARRAY
Return the given array in reverse order.
Arguments
Name | Data Type | Description |
---|---|---|
ARRAY |
array |
The array to reverse. |
Examples
{{ reverse [1,2,3] }}
[ 3, 2, 1 ]
rsort
rsort INPUT
Return the array sorted in lexical descending order.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
array |
The array to sort. |
Examples
{{ rsort ["d", "a", "c", "b"] }}
[ "d", "c", "b", "a" ]
set
set OBJECT KEY VALUE
Set a key on a given object to a value. Key can be specified as a dot.separated.list string or array of keys that describes a path in the given object, through any intermediate nested objects, down to the object where the given value will go.
Arguments
Name | Data Type | Description |
---|---|---|
OBJECT |
object |
The object to retrieve the value from |
KEY |
string, array |
The key name, path, or array of values representing path segments pointing to the value to create or modify. |
VALUE |
any |
The value to set. |
shuffle
shuffle INPUT
Return the array with the elements rearranged in random order.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
array |
The array to shuffle. |
Examples
{{ shuffle ["a", "b", "c", "d"] }}
[ "d", "c", "b", "a" ]
shuffleInPlace
shuffleInPlace INPUT [SEED]
Shuffle the input array in place, returning the seed value used to shuffle the input.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
array |
The array to shuffle. |
SEED |
int64 |
An optional seed value to generate reproducible randomization. |
slice
slice INPUT FROM TO
Return a subset of the given array. Items in an array are counted starting from zero.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
array |
The array to slice up. |
FROM |
integer |
The starting index within the given array to start returning items from. Can be negative, indicating the nth element from the end of the array (e.g: -1 means “last element”, -2 is “second from last”, and so on.). |
TO |
integer |
The end index within the given array to stop returning items from. Can be negative, indicating the nth element from the end of the array (e.g: -1 means “last element”, -2 is “second from last”, and so on.). |
Examples
{{ slice ["a", "e", "i", "o", "u"] 0 -1 }}
[ "a", "e", "i", "o", "u" ]
{{ slice ["a", "e", "i", "o", "u"] 2 -1 }}
[ "i", "o", "u" ]
{{ slice ["a", "e", "i", "o", "u"] -3 -1 }}
[ "i", "o", "u" ]
{{ slice ["a", "e", "i", "o", "u"] 1 1 }}
[ "e" ]
sliceify
sliceify INPUT
Convert the given input into an array. If the value is already an array, this just returns that array. Otherwise, it returns an array containing the given value as its only element.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
any |
The value to make into an array. |
Examples
{{ sliceify ["a", "b", "c"] }}
[ "a", "b", "c" ]
{{ sliceify 4 }}
[ 4 ]
sort
sort INPUT
Return an array sorted in lexical ascending order.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
array |
The array to sort. |
Examples
{{ sort ["d", "a", "c", "b"] }}
[ "a", "b", "c", "d" ]
sortByKey
sortByKey ARRAY KEY [EXPRESSION]
Sort the given array of objects by comparing the values of the given key for all objects.
Arguments
Name | Data Type | Description |
---|---|---|
ARRAY |
array |
The array of objects to sort. |
KEY |
string |
The name of the key on each object whose values should determine the order of the output array. |
EXPRESSION |
string |
The “{{ expression }}” to apply to the value at key from each object before determining uniqueness. Uses the same expression rules as filter |
Examples
{{ sortByKey [{"name": "bob"}, {"name": "Mallory"}, {"name": "ALICE"}] "name" }}
[ { "name": "ALICE" }, { "name": "bob" }, { "name": "Mallory" } ]
sslice
sslice
Identical to slice, but returns an array of strings.
stringify
stringify
Identical to sliceify, but converts all values to strings and returns an array of strings.
tail
tail INPUT COUNT
Return the last n items from an array.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
array |
The array to read from. |
COUNT |
integer |
The number of items to retrieve from the end of the array. |
Examples
{{ tail ["a", "b", "c", "d"] 2 }}
[ "c", "d" ]
transformValues
transformValues ARRAY KEY EXPRESSION
Return all elements of the given array of objects with the value at a key transformed by the given expression.
Arguments
Name | Data Type | Description |
---|---|---|
ARRAY |
array |
The array of objects to filter. |
KEY |
string |
The name of the key on each object in the given array to modify. |
EXPRESSION |
string |
The “{{ expression }}” to apply to the value at key from each object. Uses the same expression rules as filter |
Examples
{{ transformValues [{"name": "alice"}, {"name": "mallory"}, {"name": "bob"}] "name" "{{ upper . }}" }}
[ { "name": "ALICE" }, { "name": "MALLORY" }, { "name": "BOB" } ]
uniq
uniq INPUT
Return an array containing only unique values from the given array.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
array |
The array to unique. |
Examples
{{ uniq ["a", "a", "b", "b", "b", "c"] }}
[ "a", "b", "c" ]
uniqByKey
uniqByKey ARRAY KEY [EXPRESSION]
Return an array of objects containing only unique entries in the given array of objects. Uniqueness is determined by comparing the values at the given key for each object. The first time a value is encountered, that value’s parent object is included in the output. All subsequent objects with the same value at that key will be discarded.
Arguments
Name | Data Type | Description |
---|---|---|
ARRAY |
array |
The array of objects to filter. |
KEY |
string |
The name of the key on each object to consider for determining uniqueness. |
EXPRESSION |
string |
The “{{ expression }}” to apply to the value at key from each object before determining uniqueness. Uses the same expression rules as filter |
Examples
{{ uniqueByKey [{"id": "a", "value": 1}, {"id": "b", "value": 1}, {"id": "c", "value": 2}] "value" }}
[ { "id": "a", "value": 1 }, { "id": "c", "value": 2 } ]
Here we provide an expression that will normalize the value of the “name” field before performing the unique operation.
{{ uniqueByKey [{"name": "bob", "i": 1}, {"name": "BOB", "i": 2}, {"name": "Bob", "i": 3}] "name" "{{ upper . }}" }}
[ { "i": 1, "name": "BOB" } ]
uniqByKeyLast
uniqByKeyLast ARRAY KEY [EXPRESSION]
Identical to uniqByKey, except the last of a set of objects grouped by key is included in the output, not the first.
Arguments
Name | Data Type | Description |
---|---|---|
ARRAY |
array |
The array of objects to filter. |
KEY |
string |
The name of the key on each object to consider for determining uniqueness. |
EXPRESSION |
string |
The “{{ expression }}” to apply to the value at key from each object before determining uniqueness. Uses the same expression rules as filter |
Examples
{{ uniqByKeyLast [{"id": "a", "value": 1}, {"id": "b", "value": 1}, {"id": "c", "value": 2}] "value" }}
[ { "id": "b", "value": 1 }, { "id": "c", "value": 2 } ]
Here we provide an expression that will normalize the value of the “name” field before performing the unique operation.
{{ uniqueByKey [{"name": "bob", "i": 1}, {"name": "BOB", "i": 2}, {"name": "Bob", "i": 3}] "name" "{{ upper . }}" }}
[ { "i": 3, "name": "BOB" } ]
values
values OBJECT
Return an array of values from the given object.
Arguments
Name | Data Type | Description |
---|---|---|
OBJECT |
object |
The object to return values from. |
Examples
{{ values {"id": "a", "value": 1} }}
[ "a", 1 ]
Celestial & Astronomical Functions
Used for calculating details pertaining to the motion of celestial bodies as viewed from points on Earth.
celestial
celestial TIME LATITUDE LONGITUDE [ELEVATION]
Return extensive details about the position, timing, and motion of celestial objects at a given time and location.
Arguments
Name | Data Type | Description |
---|---|---|
TIME |
time |
The date/time of the observation. |
LATITUDE |
number |
The latitude of the observation point. |
LONGITUDE |
number |
The longitude of the observation point. |
ELEVATION |
number |
The elevation the observation point. |
Examples
{{ celestial "2021-06-29T22:45:42-04:00" 40.698828 -75.866871 }}
{ "observer": { "elevation": 0, "latitude": 40.698828, "longitude": -75.866871, "time": "2021-06-29T22:45:42-04:00" }, "sun": { "dawn": { "astronomical": "2021-06-29T03:30:13-04:00", "blue_hour": { "end": "2021-06-29T05:15:06-04:00", "start": "2021-06-29T05:02:08-04:00" }, "civil": "2021-06-29T05:02:08-04:00", "golden_hour": { "end": "2021-06-29T06:16:06-04:00", "start": "2021-06-29T05:15:06-04:00" }, "nautical": "2021-06-29T04:19:57-04:00" }, "daytime": { "end": "2021-06-29T20:38:18-04:00", "length_minutes": 902, "start": "2021-06-29T05:36:01-04:00" }, "dusk": { "astronomical": "2021-06-29T22:43:51-04:00", "blue_hour": { "end": "2021-06-29T21:12:09-04:00", "start": "2021-06-29T20:59:11-04:00" }, "civil": "2021-06-29T21:12:09-04:00", "golden_hour": { "end": "2021-06-29T20:59:11-04:00", "start": "2021-06-29T19:58:15-04:00" }, "nautical": "2021-06-29T21:54:15-04:00" }, "midnight": "2021-06-29T01:07:14-04:00", "night": { "end": "2021-06-30T05:02:40-04:00", "length_minutes": 471, "start": "2021-06-29T21:12:09-04:00" }, "noon": "2021-06-29T13:07:06-04:00", "position": { "azimuth": { "angle": 108.1, "cardinal": "E" }, "elevation": { "angle": -18.104, "refracted_angle": -18.086 }, "zenith": { "angle": 325.8, "cardinal": "NW", "refracted_angle": 325.8 } }, "state": { "blue_hour": false, "daytime": false, "golden_hour": false, "night": true, "twilight": false }, "sunrise": "2021-06-29T05:36:01-04:00", "sunset": "2021-06-29T20:38:18-04:00", "twilight": { "end": "2021-06-29T21:12:09-04:00", "start": "2021-06-29T20:38:18-04:00" } } }
Color Manipulation
Used to parse, manipulate, and adjust string representations of visible colors.
colorFromValue
colorFromValue VALUE
Consistently generate the same color from a given value of any type. This can be useful for providing automatically generated colors to represent data for which a set of predefined colors may not have significant meaning (for example: user avatars and contact lists).
Arguments
Name | Data Type | Description |
---|---|---|
VALUE |
any |
A value to generate a color for. |
Examples
{{ colorFromValue "Alice" }}
"#416C69"
colorToHSL
colorToHSL COLOR
Convert the given color to an “hsl()” or “hsla()” value.
Arguments
Name | Data Type | Description |
---|---|---|
COLOR |
string |
The color to convert. Can be specified as rgb(), rgba(), hsl(), hsla(), hsv(), hsva(), “#RRGGBB”, or “#RRGGBBAA”. |
Examples
{{ colorToHex "#FF0000" }}
"hsl(0, 100%, 50%)"
colorToHex
colorToHex COLOR
Convert the given color to a hexadecimal (“#RRGGBB”, “#RRGGBBAA”) value.
Arguments
Name | Data Type | Description |
---|---|---|
COLOR |
string |
The color to convert. Can be specified as rgb(), rgba(), hsl(), hsla(), hsv(), hsva(), “#RRGGBB”, or “#RRGGBBAA”. |
Examples
{{ colorToHex "hsl(0, 100%, 50%)" }}
"#FF0000"
colorToRGB
colorToRGB COLOR
Convert the given color to an “rgb()” or “rgba()” value.
Arguments
Name | Data Type | Description |
---|---|---|
COLOR |
string |
The color to convert. Can be specified as rgb(), rgba(), hsl(), hsla(), hsv(), hsva(), “#RRGGBB”, or “#RRGGBBAA”. |
Examples
{{ colorToHex "#FF0000" }}
"rgb(255, 0, 0)"
darken
darken COLOR PERCENT
Darken the given color by a percent [0-100].
Arguments
Name | Data Type | Description |
---|---|---|
COLOR |
string |
The base color to operate on. Can be specified as rgb(), rgba(), hsl(), hsla(), hsv(), hsva(), “#RRGGBB”, or “#RRGGBBAA”. |
PERCENT |
number |
A how much darker the color should be made. |
Examples
{{ darken "#FF0000" 15 }}
"#B30000"
definePalette
definePalette NAME [COLORS ...]
Define a new named color palette.
Arguments
Name | Data Type | Description |
---|---|---|
NAME |
string | |
COLORS |
(1+) |
A sequence of colors to add to the palette. |
Examples
{{ definePalette "rgb" "#FF0000" "#00FF00" "#0000FF" }}
null
desaturate
desaturate COLOR PERCENT
Desaturate the given color by a percent [0-100].
Arguments
Name | Data Type | Description |
---|---|---|
COLOR |
string |
The base color to operate on. Can be specified as rgb(), rgba(), hsl(), hsla(), hsv(), hsva(), “#RRGGBB”, or “#RRGGBBAA”. |
PERCENT |
number |
A how much less saturation the color should have. |
Examples
{{ desaturate "#ad4038" 20 }}
"#96544f"
lighten
lighten COLOR PERCENT
Lighten the given color by a percent [0-100].
Arguments
Name | Data Type | Description |
---|---|---|
COLOR |
string |
The base color to operate on. Can be specified as rgb(), rgba(), hsl(), hsla(), hsv(), hsva(), “#RRGGBB”, or “#RRGGBBAA”. |
PERCENT |
number |
A how much lighter the color should be made. |
Examples
{{ lighten "#FF0000" 15 }}
"#FF4D4D"
mix
mix FIRST SECOND [WEIGHT]
Mix two colors together, producing a third.
Arguments
Name | Data Type | Description |
---|---|---|
FIRST |
string |
The first color to operate on. Can be specified as rgb(), rgba(), hsl(), hsla(), hsv(), hsva(), “#RRGGBB”, or “#RRGGBBAA”. |
SECOND |
string |
The second color to operate on. Can be specified as rgb(), rgba(), hsl(), hsla(), hsv(), hsva(), “#RRGGBB”, or “#RRGGBBAA”. |
WEIGHT |
number |
A weight value [0.0, 1.0] specifying how much of the first color to include in the mix. |
Examples
{{ mix "#ad4038" "#0000ff" 0.8 }}
"#8A3360"
palette
palette INDEX [PALETTE]
Retrieve a color from a named color palette based on index. See Color Palettes for a description of pre-defined palettes.
Arguments
Name | Data Type | Description |
---|---|---|
INDEX |
integer |
The index to retrieve. If the index is larger than the number of colors in the palette, it will wrap-around to the beginning. |
PALETTE |
string |
The name of the palette to use. |
Examples
{{ palette 4 }}
"#330099"
{{ palette -1 }}
"#999900"
palettes
palettes
Returns the definition of all defined palettes.
saturate
saturate COLOR PERCENT
Saturate the given color by a percent [0-100].
Arguments
Name | Data Type | Description |
---|---|---|
COLOR |
string |
The base color to operate on. Can be specified as rgb(), rgba(), hsl(), hsla(), hsv(), hsva(), “#RRGGBB”, or “#RRGGBBAA”. |
PERCENT |
number |
A how much more saturation the color should have. |
Examples
{{ saturate "#ad4038" 20 }}
"#c42b21"
Comparison Functions
Used for comparing two values, or for returning one of many options based on a given condition.
compare
compare OPERATOR LEFT RIGHT
A generic comparison function. Accepts operators: “gt”, “ge”, “lt”, “le”, “eq”, “ne”
Arguments
Name | Data Type | Description |
---|---|---|
OPERATOR |
string |
The type of compare operation being performed. |
LEFT |
any |
The first value. |
RIGHT |
any |
The second value. |
eqx
eqx LEFT RIGHT
Return whether two values are equal (any type).
Arguments
Name | Data Type | Description |
---|---|---|
LEFT |
any |
The first value. |
RIGHT |
any |
The second value. |
Examples
{{ eqx "1" "1" }}
true
{{ eqx "1" "2" }}
false
{{ eqx "1" 1 }}
true
{{ eqx 1 1.0 }}
true
{{ eqx "1" 2 }}
false
gex
gex LEFT RIGHT
Return whether the first value is numerically or lexically greater than or equal to the second.
Arguments
Name | Data Type | Description |
---|---|---|
LEFT |
any |
The first value. |
RIGHT |
any |
The second value. |
gtx
gtx LEFT RIGHT
Return whether the first value is numerically or lexically greater than the second.
Arguments
Name | Data Type | Description |
---|---|---|
LEFT |
any |
The first value. |
RIGHT |
any |
The second value. |
lex
lex LEFT RIGHT
Return whether the first value is numerically or lexically less than or equal to the second.
Arguments
Name | Data Type | Description |
---|---|---|
LEFT |
any |
The first value. |
RIGHT |
any |
The second value. |
ltx
ltx LEFT RIGHT
Return whether the first value is numerically or lexically less than the second.
Arguments
Name | Data Type | Description |
---|---|---|
LEFT |
any |
The first value. |
RIGHT |
any |
The second value. |
match
match PATTERN VALUE
Return whether the given value matches the given regular expression.
Arguments
Name | Data Type | Description |
---|---|---|
PATTERN |
string, array |
The regular expression to match with, or an array of regular expressions (any of which may match). |
VALUE |
string |
The value to match against. |
nex
nex LEFT RIGHT
Return whether two values are not equal (any type).
Arguments
Name | Data Type | Description |
---|---|---|
LEFT |
any |
The first value. |
RIGHT |
any |
The second value. |
Examples
{{ nex "1" "1" }}
false
{{ nex "1" "2" }}
true
{{ nex "1" 1 }}
false
{{ nex 1 1.0 }}
false
{{ nex "1" 2 }}
true
switch
switch INPUT FALLBACK CRITERIA
Provide a simple inline switch-case style decision mechanism.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
any |
The value being tested. |
FALLBACK |
any |
The “default” value if none of the subsequent conditions match. |
CRITERIA |
array[if, then] |
An array of values representing possible values of input, and the value to return if input matches. Arguments are consumed as an array of value-result pairs. |
Examples
{{ switch "yellow" "danger" "yellow" "warning" "green" "success" "blue" "info" }}
"warning"
{{ switch "green" "danger" "yellow" "warning" "green" "success" "blue" "info" }}
"success"
{{ switch "blue" "danger" "yellow" "warning" "green" "success" "blue" "info" }}
"info"
{{ switch "red" "danger" "yellow" "warning" "green" "success" "blue" "info" }}
"danger"
{{ switch "potato" "danger" "yellow" "warning" "green" "success" "blue" "info" }}
"danger"
Dynamic Variables
A set of functions that allow for custom data to be set, retrieved, and removed at runtime; providing greater flexibility over standard template variables. All variables created or modified using these functions are accessible under the global $.vars object. For example, a variable set with {{ var “test” 123 }}
would be retrieved with {{ $.vars.test }}
, which would contain the integer value 123.
increment
increment
incrementByValue
incrementByValue
pop
pop
push
push NAME VALUE
Append a value to an array residing at the named variable. If the current value is nil, or the variable does not exist, the variable will be created as an array containing the provided value.If the current value exists but is not already an array, it will first be converted to one, to which the given value will be appended.
Arguments
Name | Data Type | Description |
---|---|---|
NAME |
string |
The name of the variable to append to. |
VALUE |
any |
The value to append. |
Examples
{{ push "test" 123 }}
[ 123 ]
{{ push "test" 456 }}
[ 123, 456 ]
{{ push "users.names" "Bob" }}
{ "users": { "names": [ "Alice", "Bob" ] } }
var
var NAME [VALUE]
Declare a new variable with a given name, optionally setting it to an initial value. If a value is not provided, the variable is set to a null (empty) value. You can use this behavior to clear out the value of an existing variable. The string defining the variable name is interpreted as a “dot.separated.path” that can be used to set the value in a deeply-nested objects.
Arguments
Name | Data Type | Description |
---|---|---|
NAME |
string |
The name of the variable to declare or set. |
VALUE |
any |
If specified, the value at $.vars.NAME will be set to the given value. Otherwise, it will be set to null. |
Examples
{{ var "test" }}
null
{{ var "test" "Hello" }}
"Hello"
{{ var "this.is.a.value" true }}
{ "this": { "is": { "a": { "value": true } } } }
varset
varset
Encoding and Decoding
For encoding typed data and data structures into well-known formats like JSON, CSV, and TSV.
base32
base32 INPUT
Encode the given bytes with the Base32 encoding scheme.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
string, bytes |
The value to encode. If a byte array is provided, it will be encoded directly. If a string is provided, it will converted to a byte array first, then encoded. |
Examples
{{ base32 "hello" }}
"nbswy3dp"
base58
base58
Encode the given bytes with the Base58 (Bitcoin alphabet) encoding scheme.
base64
base64 INPUT [ENCODING]
Encode the given bytes with the Base64 encoding scheme. Optionally specify the encoding mode: one of “padded”, “url”, “url-padded”, or empty (unpadded, default).
Arguments
Name | Data Type | Description | ||||||||
---|---|---|---|---|---|---|---|---|---|---|
INPUT |
string, bytes |
The value to encode. If a byte array is provided, it will be encoded directly. If a string is provided, it will converted to a byte array first, then encoded. |
||||||||
ENCODING |
string |
Specify an encoding option for generating the Base64 representation. Acceptable Values:
|
Examples
{{ base64 "hello?yes=this&is=dog#" }}
"aGVsbG8/eWVzPXRoaXMmaXM9ZG9nIw"
This is identical to the above example, but with the encoding explicitly specified.
{{ base64 "hello?yes=this&is=dog#" "standard" }}
"aGVsbG8/eWVzPXRoaXMmaXM9ZG9nIw"
{{ base64 "hello?yes=this&is=dog#" "padded" }}
"aGVsbG8/eWVzPXRoaXMmaXM9ZG9nIw=="
{{ base64 "hello?yes=this&is=dog#" "url" }}
"aGVsbG8_eWVzPXRoaXMmaXM9ZG9nIw"
{{ base64 "hello?yes=this&is=dog#" "url-padded" }}
"aGVsbG8_eWVzPXRoaXMmaXM9ZG9nIw=="
chr2str
chr2str
Takes an array of integers representing Unicode codepoints and returns the resulting string.
Examples
{{ chr2str [72, 69, 76, 76, 79] }}
"HELLO"
{{ chr2str [84, 72, 69, 82, 69] }}
"THERE"
csv
csv COLUMNS ROWS
Encode the given data as a comma-separated values document.
Arguments
Name | Data Type | Description |
---|---|---|
COLUMNS |
array[string] |
An array of values that represent the column names of the table being created. |
ROWS |
array[array[string]], array[object] |
An array of values that represent the column names of the table being created. |
hex
hex INPUT
Encode the given value as a hexadecimal string.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
string, bytes |
The value to encode. If a byte array is provided, it will be encoded in hexadecimal. If a string is provided, it will converted to a byte array first, then encoded. |
Examples
{{ hex "hello" }}
"68656c6c6f"
httpStatusText
httpStatusText
Return a human-readable description of the given HTTP error code.
Examples
{{ httpStatusText 404 }}
"Not Found"
{{ httpStatusText "404" }}
"Not Found"
{{ httpStatusText 979 }}
""
jsonify
jsonify DATA [INDENT]
Encode the given argument as a JSON document.
Arguments
Name | Data Type | Description |
---|---|---|
DATA |
any |
The data to encode as JSON. |
INDENT |
string |
The string to indent successive tiers in the document hierarchy with. |
markdown
markdown DOCUMENT [EXTENSIONS ...]
Parse the given string as a Markdown document and return it represented as HTML.
Arguments
Name | Data Type | Description | ||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
DOCUMENT |
string |
The full text of the Markdown to parse |
||||||||||||||||||||||||||||||||||
EXTENSIONS |
string(s) (1+) |
A list of zero of more Markdown extensions to enable when rendering the HTML. Acceptable Values:
|
readabilize
readabilize VALUE
Takes a raw HTML string and a readable version out of it.
Arguments
Name | Data Type | Description |
---|---|---|
VALUE |
string, HTML document object |
The document to sanitize. |
sanitize
sanitize VALUE
Takes a raw HTML string and santizes it, removing attributes and elements that can be used to evaluate scripts, but leaving the rest. Useful for preparing user-generated HTML for display.
Arguments
Name | Data Type | Description |
---|---|---|
VALUE |
string, HTML document object |
The document to sanitize. |
tsv
tsv COLUMNS ROWS
Encode the given data as a tab-separated values document.
Arguments
Name | Data Type | Description |
---|---|---|
COLUMNS |
array[string] |
An array of values that represent the column names of the table being created. |
ROWS |
array[array[string]], array[object] |
An array of values that represent the column names of the table being created. |
unbase32
unbase32 INPUT
Decode the given Base32-encoded string into bytes.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
string |
The string to decode. |
Examples
{{ unbase32 "nbswy3dp" }}
"aGVsbG8="
unbase58
unbase58
Decode the given Base58-encoded string (Bitcoin alphabet) into bytes.
unbase64
unbase64 INPUT [ENCODING]
Decode the given Base64-encoded string into bytes.
Arguments
Name | Data Type | Description | ||||||||
---|---|---|---|---|---|---|---|---|---|---|
INPUT |
string |
The string to decode. |
||||||||
ENCODING |
string |
Specify the encoding of the input string. Acceptable Values:
|
Examples
{{ unbase64 "aGVsbG8/eWVzPXRoaXMmaXM9ZG9nIw" }}
"aGVsbG8/eWVzPXRoaXMmaXM9ZG9nIw=="
This is identical to the above example, but with the encoding explicitly specified.
{{ unbase64 "aGVsbG8/eWVzPXRoaXMmaXM9ZG9nIw" "standard" }}
"aGVsbG8/eWVzPXRoaXMmaXM9ZG9nIw=="
This shows how to convert the binary data to a Unicode string (assuming it is a Unicode bytestream)
{{ chr2str (unbase64 "aGVsbG8/eWVzPXRoaXMmaXM9ZG9nIw") }}
"hello?yes=this\u0026is=dog#"
{{ unbase64 "aGVsbG8/eWVzPXRoaXMmaXM9ZG9nIw==" "padded" }}
"aGVsbG8/eWVzPXRoaXMmaXM9ZG9nIw=="
{{ unbase64 "aGVsbG8_eWVzPXRoaXMmaXM9ZG9nIw" "url" }}
"aGVsbG8/eWVzPXRoaXMmaXM9ZG9nIw=="
{{ unbase64 "aGVsbG8_eWVzPXRoaXMmaXM9ZG9nIw==" "url-padded" }}
"aGVsbG8/eWVzPXRoaXMmaXM9ZG9nIw=="
unhex
unhex INPUT
Decode the given hexadecimal string into bytes.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
string |
The value to decode into a byte array. |
Examples
{{ unhex "68656c6c6f" }}
"aGVsbG8="
unsafe
unsafe DOCUMENT
Return an unescaped raw HTML segment for direct inclusion in the rendered template output.This function bypasses the built-in HTML escaping and sanitization security features, and you almost certainly want to use sanitize instead. This is a common antipattern that leads to all kinds of security issues from poorly-constrained implementations, so you are forced to acknowledge this by typing “unsafe”.
Arguments
Name | Data Type | Description |
---|---|---|
DOCUMENT |
string |
The raw HTML snippet you sneakily want to sneak past the HTML sanitizer for reasons. |
url
url BASEURL [QUERYMAP]
Builds a URL with querystrings from the given base URL string and object.
Arguments
Name | Data Type | Description |
---|---|---|
BASEURL |
string |
The URL to modify |
QUERYMAP |
object |
A key-value object of query string values to add to the URL. |
urlFragment
urlFragment URL
Return the fragment component from the given URL.
Arguments
Name | Data Type | Description |
---|---|---|
URL |
string |
The URL to parse |
Examples
{{ urlFragment "https://example.com:8443/path/to/file.xml?lang=en&active=true#s6.9" }}
"s6.9"
urlHost
urlHost URL
Return the host[:port] portion of the given URL.
Arguments
Name | Data Type | Description |
---|---|---|
URL |
string |
The URL to parse |
Examples
{{ urlHost "https://example.com:8443/path/to/file.xml?lang=en&active=true#s6.9" }}
"example.com:8443"
{{ urlHost "https://example.com/somewhere/else/ }}
"example.com"
urlHostname
urlHostname URL
Return the hostname (without port number) portion of the given URL.
Arguments
Name | Data Type | Description |
---|---|---|
URL |
string |
The URL to parse |
Examples
{{ urlHostname "https://example.com:8443/path/to/file.xml?lang=en&active=true#s6.9" }}
"example.com"
{{ urlHostname "https://other.example.com/somewhere/else/ }}
"other.example.com"
urlPath
urlPath URL
Return the path component of the given URL.
Arguments
Name | Data Type | Description |
---|---|---|
URL |
string |
The URL to parse |
Examples
{{ urlPath "https://example.com:8443/path/to/file.xml?lang=en&active=true#s6.9" }}
"/path/to/file.xml"
urlPathDecode
urlPathDecode ENCODED
Decode a URL-encoded path.
Arguments
Name | Data Type | Description |
---|---|---|
ENCODED |
string |
The string to decode. |
urlPathEncode
urlPathEncode STRING
Encode a given string so it can be safely placed inside a URL path segment.
Arguments
Name | Data Type | Description |
---|---|---|
STRING |
string |
The string to encode. |
urlPort
urlPort URL
Return the numeric port number of the given URL.
Arguments
Name | Data Type | Description |
---|---|---|
URL |
string |
The URL to parse |
Examples
{{ urlPort "https://example.com:8443/path/to/file.xml?lang=en&active=true#s6.9" }}
8443
{{ urlPort "https://example.com/somewhere/else/ }}
443
urlQuery
urlQuery URL
Return all querystring values from the given URL.
Arguments
Name | Data Type | Description |
---|---|---|
URL |
string |
The URL to parse |
Examples
{{ urlQuery "https://example.com:8443/path/to/file.xml?lang=en&active=true#s6.9" }}
{ "active": true, "lang": "en" }
urlQueryString
urlQueryString URL KEY
Return a querystring value from the given URL.
Arguments
Name | Data Type | Description |
---|---|---|
URL |
string |
The URL to parse |
KEY |
string |
The querystring value to retrieve. |
Examples
{{ urlQueryString "https://example.com:8443/path/to/file.xml?lang=en&active=true#s6.9" "lang" }}
"en"
urlScheme
urlScheme URL
Return the scheme portion of the given URL.
Arguments
Name | Data Type | Description |
---|---|---|
URL |
string |
The URL to parse |
Examples
{{ urlScheme "https://example.com:8443/path/to/file.xml?lang=en&active=true#s6.9" }}
"https"
urldecode
urldecode ENCODED
Decode a URL-encoded string.
Arguments
Name | Data Type | Description |
---|---|---|
ENCODED |
string |
The string to decode. |
urlencode
urlencode STRING
Encode a given string so it can be safely placed inside a URL query.
Arguments
Name | Data Type | Description |
---|---|---|
STRING |
string |
The string to encode. |
File Path Manipulation
Used to parse and extract data from strings representing paths in a filesystem or tree hierarchy.
basename
basename PATH [EXTENSION]
Return the filename component of the given path.
Arguments
Name | Data Type | Description |
---|---|---|
PATH |
string |
The path to extract the filename from. |
EXTENSION |
string |
The path to extract the filename from. |
Examples
{{ basename "/this/is/my/file.jpg" }}
"file.jpg"
{{ basename "/this/is/my/file.jpg" ".jpg" }}
"file"
dir
dir [PATH]
Return a list of files and directories in path, or in the current directory if not specified.
Arguments
Name | Data Type | Description |
---|---|---|
PATH |
string |
The path to retrieve an array of children from. |
Examples
{{ dir }}
[ { "directory": false, "last_modified": "2006-01-02T15:04:05Z07:00", "mimetype": "image/jpeg", "name": "file.jpg", "path": "/this/is/my/file.jpg", "size": "124719" }, { "directory": true, "last_modified": "2006-01-02T15:04:05Z07:00", "name": "css", "path": "/this/is/my/css", "size": "4096" }, { "directory": false, "last_modified": "2006-01-02T15:04:05Z07:00", "mimetype": "text/plain", "name": "README.md", "path": "/this/is/my/README.md", "size": "11216" } ]
dirname
dirname PATH
Return the directory path component of the given path.
Arguments
Name | Data Type | Description |
---|---|---|
PATH |
string |
The path to extract the parent directory from. |
Examples
{{ dirname "/this/is/my/file.jpg" }}
"/this/is/my"
extname
extname PATH
Return the extension component of the given path (always prefixed with a dot [.]).
Arguments
Name | Data Type | Description |
---|---|---|
PATH |
string |
The path to extract the file extension from. |
Examples
{{ extname "file.jpg" }}
".jpg"
mimeparams
mimeparams FILENAME
Returns the parameters portion of the MIME type of the given filename.
Arguments
Name | Data Type | Description |
---|---|---|
FILENAME |
string |
The file to retrieve MIME parameters from. |
Examples
{{ mimetype "file.jpg" }}
{}
{{ mimetype "index.html" }}
{ "charset": "utf-8" }
mimetype
mimetype FILENAME
Returns a best guess at the MIME type for the given filename.
Arguments
Name | Data Type | Description |
---|---|---|
FILENAME |
string |
The file to determine the type of. |
Examples
{{ mimetype "file.jpg" }}
"image/jpeg"
{{ mimetype "index.html" }}
"text/html"
pathInRoot
pathInRoot PATH
Returns whether the given path falls within the Diecast serving root path.
Arguments
Name | Data Type | Description |
---|---|---|
PATH |
string |
The path to check. |
pathjoin
pathjoin [PARTS ...]
Return a string of all given path components joined together using the system path separator.
Arguments
Name | Data Type | Description |
---|---|---|
PARTS |
strings (1+) |
One or more strings or string arrays to join together into a path. |
Examples
{{ pathjoin "/this" "is/my" "file.jpg" }}
"/this/is/my/file.jpg"
pwd
pwd
Return the present working directory.
HTML Processing
Used to parse and modify HTML documents.
htmlAddClass
htmlAddClass DOCUMENT SELECTOR
Parse a given HTML document and add a CSS class to all elements matching a CSS selector.
Arguments
Name | Data Type | Description |
---|---|---|
DOCUMENT |
string |
The HTML document to parse. |
SELECTOR |
string |
A CSS selector that targets the elements that will be returned. |
htmlAttrFindReplace
htmlAttrFindReplace DOCUMENT SELECTOR ATTRIBUTE FIND REPLACE
Parse a given HTML document and locate a set of elements. For the given attribute name, perform a find and replace operation on the values.
Arguments
Name | Data Type | Description |
---|---|---|
DOCUMENT |
string |
The HTML document to parse. |
SELECTOR |
string |
A CSS selector that targets the elements that will be modified. |
ATTRIBUTE |
string |
The name of the attribute to modify on matching elements. |
FIND |
string |
A regular expression that will be used to find matching text in the affected attributes. |
REPLACE |
string |
The value that will replace any found text. Capture groups in the regular expression can be referenced using a “$”, e.g.: ${1}, ${2}, ${name}. |
htmlInner
htmlInner DOCUMENT SELECTOR
Parse a given HTML document and return the HTML content of the first element matching the given CSS selector.
Arguments
Name | Data Type | Description |
---|---|---|
DOCUMENT |
string |
The HTML document to parse. |
SELECTOR |
string |
A CSS selector that targets the element whose contents will be returned. |
htmlQuery
htmlQuery DOCUMENT SELECTOR
Parse a given HTML document and return details about all elements matching a CSS selector.
Arguments
Name | Data Type | Description |
---|---|---|
DOCUMENT |
string |
The HTML document to parse. |
SELECTOR |
string |
A CSS selector that targets the elements that will be returned. |
htmlRemove
htmlRemove DOCUMENT SELECTOR
Parse a given HTML document and remove all elements matching a CSS selector.
Arguments
Name | Data Type | Description |
---|---|---|
DOCUMENT |
string |
The HTML document to parse. |
SELECTOR |
string |
A CSS selector that targets the elements that will be returned. |
htmlRemoveClass
htmlRemoveClass DOCUMENT SELECTOR
Parse a given HTML document and remove a CSS class to all elements matching a CSS selector.
Arguments
Name | Data Type | Description |
---|---|---|
DOCUMENT |
string |
The HTML document to parse. |
SELECTOR |
string |
A CSS selector that targets the elements that will be returned. |
htmlSetAttr
htmlSetAttr DOCUMENT SELECTOR ATTRIBUTE VALUE
Parse a given HTML document and set an attribute to a given value on all elements matching a CSS selector.
Arguments
Name | Data Type | Description |
---|---|---|
DOCUMENT |
string |
The HTML document to parse. |
SELECTOR |
string |
A CSS selector that targets the elements that will be returned. |
ATTRIBUTE |
string |
The name of the attribute to modify on matching elements. |
VALUE |
any |
The value to set the matching attributes to. |
htmlTextFindReplace
htmlTextFindReplace DOCUMENT SELECTOR FIND REPLACE
Parse a given HTML document and locate a set of elements. For each matched element, perform a find and replace operation on the text content of the element (including all descendants).
Arguments
Name | Data Type | Description |
---|---|---|
DOCUMENT |
string |
The HTML document to parse. |
SELECTOR |
string |
A CSS selector that targets the elements that will be modified. |
FIND |
string |
A regular expression that will be used to find matching text in the affected attributes. |
REPLACE |
string |
The value that will replace any found text. Capture groups in the regular expression can be referenced using a “$”, e.g.: ${1}, ${2}, ${name}. |
stripHtml
stripHtml
Removes all HTML tags from a given input string, leaving behind only the textual content of the nodes. Only text nodes are preserved; attribute names and values, and comments, will be omitted.
HTTP Request Details
These functions provide access to information contained in the original HTTP client request that led to the current template being processed. These functions are useful for allowing user-specified data to drive how the output is generated.
cookie
cookie KEY [FALLBACK]
Returns the value of a cookie submitted in the request.
Arguments
Name | Data Type | Description |
---|---|---|
KEY |
string |
The name of the cookie value to retrieve. |
FALLBACK |
any |
The value to return of the named cookie is not present or is empty. |
headers
headers KEY [FALLBACK]
Returns an object containing all HTTP headers in the originating request.
Arguments
Name | Data Type | Description |
---|---|---|
KEY |
string |
The name of the request header value to retrieve. |
FALLBACK |
any |
The value to return of the named request header is not present or is empty. |
i18n
i18n KEY [LOCALE]
Return the translation text corresponding to the page’s current locale, or from an explicitly-provided locale.
Arguments
Name | Data Type | Description |
---|---|---|
KEY |
string |
The key corresponding to a translated text string in the |
LOCALE |
string |
Explicitly retrieve a value for the named locale. |
Examples
{{ i18n "homepage.greeting" }}
"Hello"
{{ i18n "homepage.greeting" "ru" }}
"Привет"
{{ i18n "homepage.greeting" # browser set to es-EC }}
"Hola"
param
param KEY_OR_INDEX [FALLBACK]
Returns a positional parameter parsed from the request URL.
Arguments
Name | Data Type | Description |
---|---|---|
KEYORINDEX |
string |
The name or integral position of the parameter to retrieve |
FALLBACK |
any |
The value to return if the key doesn’t exist or is empty. |
payload
payload [KEY]
Return either the request body in its entirety, or (if a key is given), parses the body as a data structure (according to the request Content-Type) and attempts to return the value at that key.
Arguments
Name | Data Type | Description |
---|---|---|
KEY |
string |
The key (may be deeply.nested) to retrieve from the request body after attempting to parse it. |
qs
qs KEY [FALLBACK]
Returns a single querystring value from the request URL.
Arguments
Name | Data Type | Description |
---|---|---|
KEY |
string |
The name of the query string value to retrieve. |
FALLBACK |
any |
The value to return of the named query string is not present or is empty. |
querystrings
querystrings
Returns an object containing all querystrings in the request URL.
read
read
Hashing and Cryptography
These functions provide basic cryptographic and non-cryptographic functions, including cryptographically-secure random number generation.
hash
hash CLEARTEXT ALGORITHM
Return the hash if the given value using the specified algorithm.
Arguments
Name | Data Type | Description | ||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
CLEARTEXT |
string |
The value to perform a one-way hash operation on. |
||||||||||||||
ALGORITHM |
string |
The hash algorithm to use. Acceptable Values:
|
hmac
hmac INPUT SECRET ALGORITHM
Generate an HMAC signature for the given input, secret string, and (optionally) hashing algorithm.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
string, bytes |
The input to generate an HMAC signature for. |
SECRET |
string |
The secret string to use for generating the signature. |
ALGORITHM |
string |
The name of the hashing algorithm to use for signing. |
md5
md5 CLEARTEXT
Return the MD5 hash of the given value.
Arguments
Name | Data Type | Description |
---|---|---|
CLEARTEXT |
string |
The value to perform a one-way hash operation on. |
Examples
{{ md5 "p@ssw0rd!" }}
"d5ec75d5fe70d428685510fae36492d9"
murmur3
murmur3
Hash the given data using the Murmur3 algorithm.
random
random [LOWER] [UPPER]
Generates a random number.
Arguments
Name | Data Type | Description |
---|---|---|
LOWER |
integer |
If specified, the number generated will be greater than or equal to this number. |
UPPER |
integer |
If specified, the number generated will be strictly less than this number. |
randomBytes
randomBytes COUNT
Return a random array of n bytes. The random source used is suitable for cryptographic purposes.
Arguments
Name | Data Type | Description |
---|---|---|
COUNT |
integer |
The size of the output array of random bytes to return. |
sha1
sha1 CLEARTEXT
Return the SHA-1 hash of the given value.
Arguments
Name | Data Type | Description |
---|---|---|
CLEARTEXT |
string |
The value to perform a one-way hash operation on. |
Examples
{{ sha1 "p@ssw0rd!" }}
"ee7161e0fe1a06be63f515302806b34437563c9e"
sha224
sha224 CLEARTEXT
Return the SHA-224 hash of the given value.
Arguments
Name | Data Type | Description |
---|---|---|
CLEARTEXT |
string |
The value to perform a one-way hash operation on. |
Examples
{{ sha224 "p@ssw0rd!" }}
"2d2e8b944f53164ee0aa8b1f98d75713c1b1bc6b9dd67591ef0a29e0"
sha256
sha256 CLEARTEXT
Return the SHA-256 hash of the given value.
Arguments
Name | Data Type | Description |
---|---|---|
CLEARTEXT |
string |
The value to perform a one-way hash operation on. |
Examples
{{ sha256 "p@ssw0rd!" }}
"df2191783c6f13274b7c54330a370d0480e82a8a54069b69de73cbfa69f8ea08"
sha384
sha384 CLEARTEXT
Return the SHA-384 hash of the given value.
Arguments
Name | Data Type | Description |
---|---|---|
CLEARTEXT |
string |
The value to perform a one-way hash operation on. |
Examples
{{ sha384 "p@ssw0rd!" }}
"d6d02abf2b495a6e4350fd985075c88e5a6807f8f79634ddde8529507a6145cb832f40fe0220f2af242a8a4b451fb7fc"
sha512
sha512 CLEARTEXT
Return the SHA-512 hash of the given value.
Arguments
Name | Data Type | Description |
---|---|---|
CLEARTEXT |
string |
The value to perform a one-way hash operation on. |
Examples
{{ sha512 "p@ssw0rd!" }}
"0f8ea05dd2936700d8f23d7ceb0c7dde03e8dd2dcac714eb465c658412600457ebd143bbf8a00eed47fa0a0677cf2f2ad08f882173546a647c6802ecb19aeeb9"
uuid
uuid
Generate a new Version 4 UUID as a string.
uuidRaw
uuidRaw
Generate the raw bytes of a new Version 4 UUID value.
Introspection and Reflection
Functions for inspecting runtime information about templates and Diecast itself.
templateKey
templateKey
Open the given file and retrieve the key from the page object defined in its header.
Language Highlighting
Utilities for performing syntax highlighting of source code.
highlight
highlight LANGUAGE SRC
Take source code in the given language and return marked up HTML that highlights language keywords and syntax.
Arguments
Name | Data Type | Description |
---|---|---|
LANGUAGE |
string |
The name of the language expected as input. If empty or the string “*”, a best effort will be made to detect the language. |
SRC |
string |
The source code to highlight. |
Math and Statistics
These functions implement basic mathematical and statistical operations on numbers.
abs
abs NUMBER
Return the absolute value of the given number.
Arguments
Name | Data Type | Description |
---|---|---|
NUMBER |
float, integer |
The number to operate on. |
acos
acos RADIANS
Return the arccosine of the given number (in radians).
Arguments
Name | Data Type | Description |
---|---|---|
RADIANS |
float, integer |
The value (in radians) to operate on. |
add
add [NUMBER ...]
Return the sum of all of the given values.
Arguments
Name | Data Type | Description |
---|---|---|
NUMBER |
float, integer (1+) |
The number(s) to add together. |
asin
asin RADIANS
Return the arcsine of the given number (in radians).
Arguments
Name | Data Type | Description |
---|---|---|
RADIANS |
float, integer |
The value (in radians) to operate on. |
atan
atan RADIANS
Return the arctangent of the given number (in radians).
Arguments
Name | Data Type | Description |
---|---|---|
RADIANS |
float, integer |
The value (in radians) to operate on. |
calc
calc OPERATOR [NUMBERS ...]
Perform arbitrary calculations on zero or more numbers.
Arguments
Name | Data Type | Description | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
OPERATOR |
string |
An operation to perform on the given sequence of numbers. Acceptable Values:
|
||||||||||||
NUMBERS |
float, integer (1+) |
Zero or more numbers to perform the given operation on (in order). |
ceil
ceil NUMBER
Return the greatest integer value greater than or equal to the given number.
Arguments
Name | Data Type | Description |
---|---|---|
NUMBER |
float, integer |
The number to operate on. |
cos
cos RADIANS
Return the cosine of the given number (in radians).
Arguments
Name | Data Type | Description |
---|---|---|
RADIANS |
float, integer |
The value (in radians) to operate on. |
deg2rad
deg2rad DEGREES
Return the given number of degrees in radians.
Arguments
Name | Data Type | Description |
---|---|---|
DEGREES |
float, integer |
The value (in degrees) to convert. |
divide
divide [NUMBER ...]
Sequentially divide all of the given values in the order given.
Arguments
Name | Data Type | Description |
---|---|---|
NUMBER |
float, integer (1+) |
The number(s) to divide, in order. |
floor
floor NUMBER
Return the greatest integer value less than or equal to the given number.
Arguments
Name | Data Type | Description |
---|---|---|
NUMBER |
float, integer |
The number to operate on. |
isEven
isEven NUMBER
Return whether the given number is even.
Arguments
Name | Data Type | Description |
---|---|---|
NUMBER |
float, integer |
The number to test. |
isOdd
isOdd NUMBER
Return whether the given number is odd.
Arguments
Name | Data Type | Description |
---|---|---|
NUMBER |
float, integer |
The number to test. |
maximum
maximum NUMBERS
Return the maximum of the given array of numbers.
Arguments
Name | Data Type | Description |
---|---|---|
NUMBERS |
array[float, integer] |
An array of numbers to aggregate. |
mean
mean NUMBERS
Return the mean of the given array of numbers.
Arguments
Name | Data Type | Description |
---|---|---|
NUMBERS |
array[float, integer] |
An array of numbers to aggregate. |
median
median NUMBERS
Return the median of the given array of numbers.
Arguments
Name | Data Type | Description |
---|---|---|
NUMBERS |
array[float, integer] |
An array of numbers to aggregate. |
minimum
minimum NUMBERS
Return the minimum of the given array of numbers.
Arguments
Name | Data Type | Description |
---|---|---|
NUMBERS |
array[float, integer] |
An array of numbers to aggregate. |
minimum_nz
minimum_nz NUMBERS
Return the minimum (excluding zero) of the given array of numbers.
Arguments
Name | Data Type | Description |
---|---|---|
NUMBERS |
array[float, integer] |
An array of numbers to aggregate. |
mod
mod [NUMBER ...]
Return the modulus of all of the given values.
Arguments
Name | Data Type | Description |
---|---|---|
NUMBER |
float, integer (1+) |
The number(s) to operate on, in order. |
multiply
multiply [NUMBER ...]
Return the product of all of the given values.
Arguments
Name | Data Type | Description |
---|---|---|
NUMBER |
float, integer (1+) |
The number(s) to multiply together. |
negate
negate NUMBER
Return the given number multiplied by -1.
Arguments
Name | Data Type | Description |
---|---|---|
NUMBER |
float, integer |
The number to operate on. |
pow
pow [NUMBER ...]
Sequentially exponentiate of all of the given values.
Arguments
Name | Data Type | Description |
---|---|---|
NUMBER |
float, integer (1+) |
The number(s) to operate on, in order. |
rad2deg
rad2deg RADIANS
Return the given number of radians in degrees.
Arguments
Name | Data Type | Description |
---|---|---|
RADIANS |
float, integer |
The value (in radians) to convert. |
round
round NUMBER
Round a number to the nearest n places.
Arguments
Name | Data Type | Description |
---|---|---|
NUMBER |
float, integer |
The number to round. |
sequence
sequence END [START]
Return an array of integers representing a sequence from [0, n).
Arguments
Name | Data Type | Description |
---|---|---|
END |
integer |
The largest number in the sequence (exclusive). |
START |
integer |
The number to start the sequence at (inclusive) |
sin
sin RADIANS
Return the sine of the given number (in radians).
Arguments
Name | Data Type | Description |
---|---|---|
RADIANS |
float, integer |
The value (in radians) to operate on. |
stddev
stddev NUMBERS
Return the standard deviation of the given array of numbers.
Arguments
Name | Data Type | Description |
---|---|---|
NUMBERS |
array[float, integer] |
An array of numbers to aggregate. |
subtract
subtract [NUMBER ...]
Sequentially subtract all of the given values.
Arguments
Name | Data Type | Description |
---|---|---|
NUMBER |
float, integer (1+) |
The number(s) to subtract, in order. |
sum
sum NUMBERS
Return the sum of the given array of numbers.
Arguments
Name | Data Type | Description |
---|---|---|
NUMBERS |
array[float, integer] |
An array of numbers to aggregate. |
tan
tan RADIANS
Return the tangent of the given number (in radians).
Arguments
Name | Data Type | Description |
---|---|---|
RADIANS |
float, integer |
The value (in radians) to operate on. |
String Functions
Used to modify strings in various ways. Whitespace trimming, substring and concatenation, conversion, and find & replace functions can all be found here.
autobyte
autobyte BYTES FORMAT
Attempt to convert the given number to a string representation of the value interpreted as bytes. The unit will be automatically determined as the closest one that produces a value less than 1024 in that unit. The second argument is a printf-style format string that is used when the converted number is being stringified. By specifying precision and leading digit values to the %f format token, you can control how many decimal places are in the resulting output.
Arguments
Name | Data Type | Description |
---|---|---|
BYTES |
number |
A number representing the value to format, in bytes. |
FORMAT |
string |
A printf-style format string used to represent the output number. |
Examples
{{ autobyte 2490368 "%.2f" }}
"2.38MB"
{{ autobyte 9876543210 "%.0f " }}
"9 GB"
camelize
camelize IN
Reformat the given string by changing it into camelCase capitalization.
Arguments
Name | Data Type | Description |
---|---|---|
IN |
string |
The input string to reformat. |
Examples
{{ camelize "This is a thing" }}
"thisIsAThing"
concat
concat [VALUES ...]
Return the string that results in stringifying and joining all of the given arguments.
Arguments
Name | Data Type | Description |
---|---|---|
VALUES |
any (1+) |
One or more values to be stringified and joined together. |
Examples
{{ concat "There are " 5 " apples, yes it's " true }}
"There are 5 apples, yes it's true."
contains
contains INPUT SUBSTRING
Return true of the given string contains another string.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
string |
The string to search within. |
SUBSTRING |
string |
The substring to find in the input string. |
Examples
{{ contains "Alice met Bob at the store." "store" }}
"true"
elide
elide INPUT CHARCOUNT
Takes an input string and ensures it is no longer than a given number of characters.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
string |
The string to (possibly) truncate. |
CHARCOUNT |
integer |
The maximum number of characters that can appear in a string before it is truncated. |
Examples
{{ elide "This is a sentence that contains fifty characters." 18 }}
"This is a sentence"
{{ elide "hello." 16 }}
"hello."
elideWords
elideWords INPUT WORDCOUNT
Takes an input string and counts the number of words in it. If that number exceeds a given count, the string will be truncated to be equal to that number of words.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
string |
The string to (possibly) truncate. |
WORDCOUNT |
integer |
The maximum number of words that can appear in a string before it is truncated. |
Examples
{{ elideWords "This is a sentence that contains eight words." 5 }}
"This is a sentence that"
{{ elideWords "Hello world" 10 }}
"Hello world"
emoji
emoji EMOJI FALLBACK
Expand the given named emoji into its literal Unicode character.
Arguments
Name | Data Type | Description |
---|---|---|
EMOJI |
string |
The common name of the emoji to return, with or without surrounding colons (:). |
FALLBACK |
string |
What to return if the named emoji is not found. |
Examples
{{ emoji ":thinking_face:" }}
"🤔"
{{ emoji ":not_a_real_emoji:" "nope" }}
"nope"
emojis
emojis [NAMES ...]
Return an object containing all known emoji, keyed on the well-known names used to refer to them.
Arguments
Name | Data Type | Description |
---|---|---|
NAMES |
string (1+) |
A list of zero or more emoji to return from the whole list. |
Examples
{{ emoji ":thinking_face:" }}
"🤔"
{{ emoji ":not_a_real_emoji:" "nope" }}
"nope"
hasPrefix
hasPrefix IN PREFIX
Return true if the given string begins with the given prefix.
Arguments
Name | Data Type | Description |
---|---|---|
IN |
string |
The input string to test. |
PREFIX |
string |
The prefix to test for the presence of. |
hasSuffix
hasSuffix IN SUFFIX
Return true if the given string ends with the given suffix.
Arguments
Name | Data Type | Description |
---|---|---|
IN |
string |
The input string to test. |
SUFFIX |
string |
The suffix to test for the presence of. |
hyphenate
hyphenate IN
Reformat the given string by changing it into hyphen-case capitalization.
Arguments
Name | Data Type | Description |
---|---|---|
IN |
string |
The input string to reformat. |
Examples
{{ hyphenate "This is a thing" }}
"this-is-a-thing"
join
join INPUT SEPARATOR [OUTER_DELIMITER]
Stringify the given array of values and join them together into a string, separated by a given separator string.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
array[any] |
An array of values to stringify and join. |
SEPARATOR |
string |
The string used to join all elements of the array together. |
OUTERDELIMITER |
string |
If given an object, this string will be used to join successive key-value pairs. |
Examples
{{ join [1, 2, 3] "," }}
"1,2,3"
{{ join {"a": 1, "b": 2, "c": 3} "=" "&" }}
"a=1\u0026b=2\u0026c=3"
lipsum
lipsum WORDS
Return the given number of words from the “Lorem ipsum” example text.
Arguments
Name | Data Type | Description |
---|---|---|
WORDS |
integer |
The number of words to return. |
longestString
longestString ARRAY
Return the string in the given array that is longest.
Arguments
Name | Data Type | Description |
---|---|---|
ARRAY |
string |
The array of strings to scan. |
lower
lower IN
Reformat the given string by changing it into lower case capitalization.
Arguments
Name | Data Type | Description |
---|---|---|
IN |
string |
The input string to reformat. |
Examples
{{ lower "This is a thing" }}
"this is a thing"
ltrim
ltrim IN
Return the given string with any leading whitespace removed.
Arguments
Name | Data Type | Description |
---|---|---|
IN |
string |
The input string to trim. |
Examples
{{ trim " Hello World " }}
"Hello World "
pascalize
pascalize IN
Reformat the given string by changing it into PascalCase capitalization.
Arguments
Name | Data Type | Description |
---|---|---|
IN |
string |
The input string to reformat. |
Examples
{{ pascalize "This is a thing" }}
"ThisIsAThing"
percent
percent VALUE WHOLE [FORMAT]
Takes an integer or decimal value and returns it formatted as a percentage.
Arguments
Name | Data Type | Description |
---|---|---|
VALUE |
number |
The value you wish to express as a percentage. |
WHOLE |
number |
The number that represents 100%. |
FORMAT |
string |
The printf format string used for rounding and truncating the converted number. |
Examples
{{ percent 99 }}
"99"
{{ percent 3.3 10 }}
"33"
{{ percent 3.33 10 "%.3f" }}
"33.300"
replace
replace WHOLESTRING OLD NEW COUNT
Replace occurrences of one substring with another string in a given input string.
Arguments
Name | Data Type | Description |
---|---|---|
WHOLESTRING |
string |
The whole string being searched. |
OLD |
string |
The old value being sought. |
NEW |
string |
The new value that is replacing old. |
COUNT |
integer |
The number of matches to replace before stopping. If this number is < 0, the all occurrences will be replaced. |
Examples
{{ replace "oink oink oink" "oink" "moo" -1 }}
"moo moo moo"
{{ replace "cheese" "e" "o" 2 }}
"choose"
rtrim
rtrim IN
Return the given string with any trailing whitespace removed.
Arguments
Name | Data Type | Description |
---|---|---|
IN |
string |
The input string to trim. |
Examples
{{ trim " Hello World " }}
" Hello World"
rxreplace
rxreplace WHOLESTRING PATTERN REPL
Return the given string with all substrings matching the given regular expression replaced with another string.
Arguments
Name | Data Type | Description |
---|---|---|
WHOLESTRING |
string |
The whole string being searched. |
PATTERN |
string |
A Golang-compatible regular expression that matches what should be replaced. |
REPL |
string |
The string to replace matches with. |
Examples
{{ rxreplace "<b>Hello <i>World</i></b>" "</?[bi]>" "*" }}
"*Hello *World**"
section
section INPUT FIELD [SPLIT]
Takes an input string, splits it on a given regular expression, and returns the nth field.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
string |
The string to retrieve the field from. |
FIELD |
integer |
The number of the field to retrieve after splitting input. |
SPLIT |
string |
A regular expression to use when splitting the string. |
Examples
{{ section "this|is|a|row" 1 "|" }}
"this"
{{ section "this|is|a|row" 2 "|" }}
"is"
shortestString
shortestString ARRAY
Return the string in the given array that is shortest (excluding empty strings).
Arguments
Name | Data Type | Description |
---|---|---|
ARRAY |
string |
The array of strings to scan. |
split
split IN SEPARATOR
Split a given string into an array of strings by a given separator.
Arguments
Name | Data Type | Description |
---|---|---|
IN |
string |
The string to split into pieces. |
SEPARATOR |
string |
The separator on which the input will be split. |
Examples
{{ split "this is a sentence." }}
[ "this", "is", "a", "sentence." ]
splitWords
splitWords
Detect word boundaries in a given string and split that string into an array where each element is a word.
strcount
strcount
Count counts the number of non-overlapping instances of a substring. If the given substring is empty, then this returns the length of the string plus one.
surroundedBy
surroundedBy INPUT PREFIX SUFFIX
Return whether the given string is begins with a specific prefix and ends with a specific suffix.
Arguments
Name | Data Type | Description |
---|---|---|
INPUT |
string |
The string to test. |
PREFIX |
string |
A string to prepend to the given input string. |
SUFFIX |
string |
A string to append to the given input string. |
Examples
{{ surroundedBy "<table>" "<" ">" }}
true
thousandify
thousandify
Take a number and reformat it to be more readable by adding a separator between every three successive places.
titleize
titleize
Reformat the given string by changing it into Title Case capitalization.
trim
trim IN [CHARACTERS]
Return the given string with any leading and trailing whitespace or characters removed.
Arguments
Name | Data Type | Description |
---|---|---|
IN |
string |
The input string to trim. |
CHARACTERS |
string |
A sequence of characters to trim from the string. |
Examples
{{ trim " Hello World " }}
"Hello World"
{{ trim "'hello world'" "'" }}
"hello world"
underscore
underscore IN
Reformat the given string by changing it into _underscorecase_ capitalization (also known as snake_case).
Arguments
Name | Data Type | Description |
---|---|---|
IN |
string |
The input string to reformat. |
Examples
{{ underscore "This is a thing" }}
"this_is_a_thing"
upper
upper IN
Reformat the given string by changing it into UPPER CASE capitalization.
Arguments
Name | Data Type | Description |
---|---|---|
IN |
string |
The input string to reformat. |
Examples
{{ upper "This is a thing }}
"THIS IS A THING"
Time Functions
Used for working with time and duration values. Among this collection are functions for converting values to times, formatting time values, and performing time-oriented calculations on those values.
addTime
addTime DURATION [FROM]
Return a time with with given duration added to it. Can specify time at to apply the change to. Defaults to the current time.
Arguments
Name | Data Type | Description |
---|---|---|
DURATION |
string |
The duration to add to the time (can be negative to subtract a duration). See Time Durations for how to specify durations. |
FROM |
string |
If specified, this time will be parsed and modified instead of the current time. |
Examples
{{ addTime "2h30m" }}
"2010-05-01T15:34:00-05:00"
{{ addTime "-14d" "2011-10-21T12:00:00-08:00" }}
"2011-10-07T12:00:00-08:00"
ago
ago DURATION [FROM]
Return a new time subtracted by the given duration.
Arguments
Name | Data Type | Description |
---|---|---|
DURATION |
string |
The duration to subtract from the starting time. |
FROM |
string, time |
The starting time to subtract a duration from. |
Examples
{{ ago "1d" }}
"2006-01-01 15:04:05Z07:00"
{{ ago "45d" "2020-02-15T00:00:00Z" }}
"2020-01-01 00:00:00 +0000 UTC"
duration
duration DURATION UNIT [FORMAT]
Convert the given value from a duration (specified with the given unit) into the given time format.
Arguments
Name | Data Type | Description | ||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
DURATION |
integer, duration |
A duration of time |
||||||||||||||||
UNIT |
string |
The unit of time the given duration is expressed in. If a “duration” type is given, this may be an empty string. Acceptable Values:
|
||||||||||||||||
FORMAT |
string |
How to format the time output. See Time Formats for how to use format strings. |
Examples
{{ duration 127 "s" }}
"0001-01-01 00:02:07 +0000 UTC"
{{ duration 127 "s" "kitchen" }}
"12:02AM"
{{ duration 127 "s" "15:04:05" }}
"00:02:07"
{{ duration 127 "s" "timer" }}
"02:07"
extractTime
extractTime VALUE
Attempt to extract a time value from the given string.
Arguments
Name | Data Type | Description |
---|---|---|
VALUE |
string |
A string that will be scanned for values that look like dates and times. |
isAfter
isAfter FIRST SECOND
Return whether the first time occurs after the second one.
Arguments
Name | Data Type | Description |
---|---|---|
FIRST |
string, time |
The time to compare against. |
SECOND |
string, time |
The time being checked. |
isBefore
isBefore FIRST SECOND
Return whether the first time occurs before the second one.
Arguments
Name | Data Type | Description |
---|---|---|
FIRST |
string, time |
The time to compare against. |
SECOND |
string, time |
The time being checked. |
isBetweenTimes
isBetweenTimes FIRST SECOND [REFERENCE]
Return whether a time is between two times [first, second).
Arguments
Name | Data Type | Description |
---|---|---|
FIRST |
string, time |
The lower bound. |
SECOND |
string, time |
The upper bound. |
REFERENCE |
string, time |
If provided, this time will be used to check the given times instead of the current time. |
isNewerThan
isNewerThan TIME DURATION [REFERENCE]
Return whether the time between now and the given time is less than or equal to now minus the given duration.
Arguments
Name | Data Type | Description |
---|---|---|
TIME |
string, time |
The time being checked. |
DURATION |
string, duration |
The duration being checked. |
REFERENCE |
string, time |
If provided, this time will be used to check the given times instead of the current time. |
isOlderThan
isOlderThan TIME DURATION [REFERENCE]
Return whether the time between now and the given time is greater than now minus the given duration.
Arguments
Name | Data Type | Description |
---|---|---|
TIME |
string, time |
The time being checked. |
DURATION |
string, duration |
The duration being checked. |
REFERENCE |
string, time |
If provided, this time will be used to check the given times instead of the current time. |
now
now [FORMAT]
Return the current time, optionally formatted using the given format.
Arguments
Name | Data Type | Description |
---|---|---|
FORMAT |
string |
How to format the time output. See Time Formats for how to use format strings. |
Examples
{{ now }}
"2010-05-01T13:04:00-05:00"
{{ now "ansic" }}
"Mon Jan 2 22:04:05 2006"
since
since FROM [INTERVAL]
Return the amount of time that has elapsed since the given time, optionally rounded to the nearest time interval.
Arguments
Name | Data Type | Description | ||||||||
---|---|---|---|---|---|---|---|---|---|---|
FROM |
string |
The time to use when determining the duration that time has elapsed from. |
||||||||
INTERVAL |
string |
If specified, the resulting time duration will be rounded to the nearest interval of this unit. Can be one of: “second” (nearest second), “minute” (nearest minute), “hour” (nearest hour), or “day” (nearest day). Acceptable Values:
|
Examples
{{ since "2010-05-01T13:04:15-05:00 }}
""
{{ since "-14d" "2011-10-21T12:00:00-08:00" }}
"2011-10-07T12:00:00-08:00"
sunrise
sunrise LATITUDE LONGITUDE [REFERENCE]
Return the time of apparent sunrise at the given coordinates, optionally for a given time.
Arguments
Name | Data Type | Description |
---|---|---|
LATITUDE |
float |
The latitude to retrieve the time for. |
LONGITUDE |
float |
The longitude to retrieve the time for. |
REFERENCE |
string, time |
If provided, this time will be used for the calculation instead of the current time. |
sunset
sunset LATITUDE LONGITUDE [REFERENCE]
Return the time of apparent sunset at the given coordinates, optionally for a given time.
Arguments
Name | Data Type | Description |
---|---|---|
LATITUDE |
float |
The latitude to retrieve the time for. |
LONGITUDE |
float |
The longitude to retrieve the time for. |
REFERENCE |
string, time |
If provided, this time will be used for the calculation instead of the current time. |
time
time TIME
Return the given time formatted using a given format. See Time Formats for acceptable formats.
Arguments
Name | Data Type | Description |
---|---|---|
TIME |
string, integer |
The time you want to format. Parsing is extremely flexible, and can handle dates represented as RFC3339, RFC822, RFC1123, epoch, or epoch nanoseconds. |
Examples
{{ time "01 May 10 13:04 -0500" "rfc3339" }}
"2010-05-01T13:04:00-05:00"
{{ time 1136239445 "ansic" }}
"Mon Jan 2 22:04:05 2006"
timeBetween
timeBetween FIRST SECOND
Return the duration of time between the first time minus the second time.
Arguments
Name | Data Type | Description |
---|---|---|
FIRST |
string, time |
The first time being computed. |
SECOND |
string, time |
The second time being computed. |
Type Detection and Manipulation
Used to detect and convert discrete values into different data types.
asBool
asBool
Attempt to convert the given value to a boolean value.
asDuration
asDuration
Attempt to parse the given value as a time duration.
asFloat
asFloat
Attempt to convert the given value to a floating-point number.
asInt
asInt
Attempt to convert the given value to an integer.
asStr
asStr
Return the value as a string.
asTime
asTime
Attempt to parse the given value as a date/time value.
autotype
autotype
Attempt to automatically determine the type if value and return the converted output.
isArray
isArray
Return whether the given value is an iterable array or slice.
isBool
isBool
Return whether the given value is a boolean type.
isDuration
isDuration
Return whether the given value is parsable as a duration.
isEmpty
isEmpty
Return whether the given value is empty.
isFloat
isFloat
Return whether the given value is a floating-point type.
isInt
isInt
Return whether the given value is an integer type.
isMap
isMap
Return whether the given value is a key-value map type.
isNotEmpty
isNotEmpty
Return whether the given value is NOT empty.
isNotZero
isNotZero
Return whether the given value is NOT a zero-valued variable.
isTime
isTime
Return whether the given value is parsable as a date/time value.
isZero
isZero
Return whether the given value is an zero-valued variable.
Unit Conversions
Used to convert numeric values between different unit systems.
convert
convert
A generic unit conversion function that allows for units to be specified by value as strings.
Appendix
Time Formats
A special string can be used to specify how a given date value should be formatted for display. Diecast supports the same syntax as Golang’s time.Format function, as well as additional commonly-used formats.
Predefined Formats
Format String | Example |
---|---|
kitchen |
“3:04PM” |
timer |
“15:04:05” |
rfc3339 |
“2006-01-02T15:04:05Z07:00” |
rfc3339ns |
“2006-01-02T15:04:05.999999999Z07:00” |
rfc822 |
“02 Jan 06 15:04 MST” |
rfc822z |
“02 Jan 06 15:04 -0700” |
rfc1123 |
“Mon, 02 Jan 2006 15:04:05 MST” |
rfc1123z |
“Mon, 02 Jan 2006 15:04:05 -0700” |
epoch |
“1136239445” |
epoch-ms |
“1136239445999” |
epoch-us |
“1136239445999999” |
epoch-ns |
“1136239445999999999” |
day |
“Monday” |
slash |
“01/02/2006” |
slash-dmy |
“02/01/2006” |
ymd |
“2006-01-02” |
ruby |
“Mon Jan 02 15:04:05 -0700 2006” |
ansic |
“Mon Jan _2 15:04:05 2006” |
ruby |
“Mon Jan 02 15:04:05 -0700 2006” |
unixdate |
“Mon Jan _2 15:04:05 MST 2006” |
stamp |
“Jan _2 15:04:05” |
stamp-ms |
“Jan _2 15:04:05.000” |
stamp-us |
“Jan _2 15:04:05.000000” |
stamp-ns |
“Jan _2 15:04:05.000000000” |
Custom Formats
You can also specify a custom format string by using the components the the reference date as an
example to Diecast on how to translate the given date into the output you want. The reference
date/time is: Mon Jan 2 15:04:05 MST 2006
. In the predefined formats above, the examples given all
use this reference date/time, and you can refer to those formats for building your own strings.
For example, given the date 2018-03-10T16:30:00, and the custom format string “Mon, January _1, 2006”, that date would be displayed as “Sat, March 10, 2018”. The format was built by providing examples from the reference date on how to do the conversion. The values used in the reference date have been carefully chosen to avoid any ambiguity when specifying custom formats.
Wildcard Patterns
Throughout the application, certain configuration options support a way to specify wildcard patterns that match more than just a specific string. These types of patterns are especially useful when working with URLs, where it is common to want settings to apply to all URLs that start with or otherwise contain a specific string. Below is a description of the wildcard support Diecast implements:
Pattern | Example | Description |
---|---|---|
* |
/api/* |
Match zero or more non-separator characters (/ ). |
** |
/api/** |
Match zero or more characters, including separators. |
? |
/api/? |
Match zero or one character. |