Subsections of Built-in helper functions

Strings

Name Description Function arguments Usage
replaceAll Replace all occurrences of the input in the text replaceAll(myText, lookFor, replaceWith) {{ replaceAll “test-string-test” “test” “new” }}
replace Replace the input text occurrences the given amount of times replace(myText, lookFor, replaceWith, times) {{ replace “test-string-test” “test” “new” 1 }}
repeat Repeat the given string the input amount of times repeat(myText, times) {{ repeat “my-string” 10 }}
trimSpace Remove trailing spaces trimSpace(myText) {{ trimSpace " my-StRing " }}
containsStr Check if string contains substring containsStr(str, part) bool {{ containsStr “my-StRing” “my” }}
startsStr Check if string have prefix startsStr(str, prefix) bool {{ startsStr “my-StRing” “my” }}
endsStr Check if string have suffix endsStr(str, suffix) bool {{ endsStr “my-StRing” “ing” }}
toLower Convert all characters to lower case toLower(myText) {{ toLower “my-StRing” }}
toUpper Convert all characters to upper case toUpper(myText) {{ toUpper “my-StRing” }}
toTitle Convert the text to title case toTitle(myText) {{ toTitle “my-StRing” }}
split Convert a string to a string array split(myText, separator) {{ split “one,two” “,” }}
splitN Convert a string to a string array with max splits splitN(myText, separator, times) {{ split “one,two,three” “,” 1 }}
hash Hash encoding, supported types: md5, sha1, sha256, sha512 hash(str, type) string {{ hash “my-StRing” “sha256” }}
encode Basic encoding, supported types: base32, base64, hex encode(str, type) string {{ encode “my-StRing” “base64” }}
decode Basic decoding, supported types: base32, base64, hex decode(str, type) string {{ decode “my-StRing” “base64” }}
hmac HMAC encoding, supported types: md5, sha1, sha256, sha512 hmac(str, key, type) string {{ hmac “my-StRing” “sec-key” “sha256” }}
html encapsulates a known safe HTML document fragment html(htmlStr) string {{ html “
trusted html
” }}
htmlAttr encapsulates an HTML attribute from a trusted source htmlAttr(htmlAttrStr) string {{ htmlAttr `dir=“ltr”` }}
urlSrc encapsulates a known safe URL or URL substring urlSrc(urlStr) string {{ urlSrc “/trusted/url” }}
uuid generates UUID V4 uuid() string {{ uuid }}
transformToCp Converts UTF-8 string to the one of desired code page options transformToCp(source, codepage) string {{ transformToCp “¡¢£” “iso8859_1” }}

The functions that accept a single parameter can also be used with the pipe notation.

<p>{{ "my-StRing" | toLower | trimSpace }}</p>
<!-- Results in: "my-string" -->

Supported code pages for transformToCp

Code page
cp037
cp437
cp850
cp852
cp855
cp858
cp860
cp862
cp863
cp865
cp866
cp1047
iso8859_1
iso8859_2
iso8859_3
iso8859_4
iso8859_5
iso8859_6
iso8859_7
iso8859_8
iso8859_9
iso8859_10
iso8859_13
iso8859_14
iso8859_15
iso8859_16
koi8r
koi8u
macintosh
macintoshcyrillic
windows874
windows1250
windows1251
windows1252
windows1253
windows1254
windows1255
windows1256
windows1257
windows1258

Dates

The date formatting feature uses the go date formatting, as such the same format layouts are expected. Check https://gosamples.dev/date-time-format-cheatsheet/ for information on how the form the formats. Default format 2006-01-02T15:04:05Z07:00. Some dt prefixed functions returns timeObject, which is golang struct. This struct may be used while calling multiple functions in a pipe, check examples for how-to-use tips. All timeObject related functions description could be found on the official golang documentation portal. Check all functions that starts from func (t Time).

Almost every account have default time related configurations, like timezone and formats. Timezone may not exist for accounts that shares many timezones (e.g. most of the USA accounts), in this case timezone should be configured by account owners.

Available variables:

{{ $timeZone := .Data.ErplyApi.ConfigurationList.timezone }} <!-- Europe/Tallinn -->
{{ $dateFormat := .Data.ErplyApi.ConfigurationList.go_date_format }} <!-- 02.01.2006 -->
{{ $monthDayFormat := .Data.ErplyApi.ConfigurationList.go_month_day_format }} <!-- 02.01 -->
{{ $timeFormat := .Data.ErplyApi.ConfigurationList.go_time_format }} <!-- 15:04:05 -->
{{ $hourMinuteFormat := .Data.ErplyApi.ConfigurationList.go_hour_minute_format }} <!-- 15:04 -->
{{ $dateTimeFormat := .Data.ErplyApi.ConfigurationList.go_date_time_format }} <!-- 02.01.2006 15:04:05 -->

Duration formatting syntax

The duration formatting feature partially inherits the go time formatting, so those are placeholders:

  • 00 - years
  • 01 - months
  • 02 - days
  • 03 - hours
  • 04 - minutes
  • 05 - seconds

Sample usage:

{{ formatDuration "2450000m35s" "00 year(s) 01 month(s) 02 day(s) 03 hour(s) 04 minute(s) and 05 second(s)" }}
<!-- Result: 4 year(s) 8 month(s) 1 day(s) 9 hour(s) 20 minute(s) and 35 second(s) -->
Name Description Function arguments Usage
unixToDate Convert a unix value to the requested date format in the selected timezone unixToDate(unix, timeZone, format) string {{ unixToDate 150000 “UTC” “2006-01-02” }}
formatDate Convert one specific date format to another formatDate(dateValue, fromFormat, toFormat, timeZone) string {{ formatDate “2022-11-11” “2006-01-02” “2006/02/01” “GMT” }}
serverTime Returns unix time in seconds serverTime() int64 {{ serverTime }}
serverTimeIn Returns current datetime in provided timezone and format serverTimeIn(timeZone, format) string {{ serverTimeIn “GMT” “2006-01-02” }}
addDate Adds amount of unitOfTime to the datetime and returns datetime in default format addDate(datetime, unitOfTime, amount) string {{ addDate “2023-01-02” “month” -6 }}
addDate same as previous, but with optional format parameter addDate(datetime, unitOfTime, amount, format) string {{ addDate “2023-01-02” “month” 6 “2006/02/01” }}
dtFromDateTime To get timeObject from the datetime dtFromDateTime(datetime, format, timezone) timeObject {{ dtFromDateTime “2023-01-02” “2006-01-02” “GMT” }}
dtCurrent Current time (returns default format) dtCurrent() timeObject {{ dtCurrent }}
dtCurrentIn Current time in TZ (returns default format) dtCurrentIn(timezone) timeObject {{ dtCurrentIn “GMT” }}
dtAdjustDate add or subtract unit of time to/from datetime dtAdjustDate(timeObject, unitOfTime, amount) timeObject {{ dtAdjustDate timeObject “month” 6}}
dtFirstDayOfWeek First day of week, if isSunday true then week starts from Sunday dtFirstDayOfWeek(timeObject, isSunday) timeObject {{ dtFirstDayOfWeek timeObject false }}
dtLastDayOfWeek Last day of week, if isSunday true then week starts from Sunday dtLastDayOfWeek(timeObject, isSunday) timeObject {{ dtLastDayOfWeek timeObject false }}
dtFirstDayOfMonth First day of month dtFirstDayOfMonth(timeObject) timeObject {{ dtFirstDayOfMonth timeObject }}
dtLastDayOfMonth Last day of month dtLastDayOfMonth(timeObject) timeObject {{ dtLastDayOfMonth timeObject }}
dtFirstDayOfYear First day of the year dtFirstDayOfYear(timeObject) timeObject {{ dtFirstDayOfYear timeObject }}
dtLastDayOfYear Last day of the year dtLastDayOfYear(timeObject) timeObject {{ dtLastDayOfYear timeObject }}
dtToFormat Convert timeObject to string using format dtToFormat(timeObject, format) string {{ dtToFormat timeObject “2006/02/01” }}
dtToTimezone Set timeObject into a different timezone dtToTimezone(timeObject, timezone) timeObject {{ dtToTimezone timeObject “UTC” }}
dtToFormatIn Set timezone and format at the same time dtToFormatIn(timeObject, format, timezone) string {{ dtToFormatIn timeObject “2006/02/01” “UTC” }
dtFirstDayOfPreviousMonthInFormat Datetime manipulation in format, returns string dtFirstDayOfPreviousMonthInFormat(timeObject, format) string {{ dtFirstDayOfPreviousMonthInFormat timeObject “2006/02/01” }}
dtFirstDayOfCurrentMonthInFormat Datetime manipulation in format, returns string dtFirstDayOfCurrentMonthInFormat(timeObject, format) string {{ dtFirstDayOfCurrentMonthInFormat timeObject “2006/02/01” }}
dtFirstDayOfNextMonthInFormat Datetime manipulation in format, returns string dtFirstDayOfNextMonthInFormat(timeObject, format) string {{ dtFirstDayOfNextMonthInFormat timeObject “2006/02/01” }}
dtLastDayOfPreviousMonthInFormat Datetime manipulation in format, returns string dtLastDayOfPreviousMonthInFormat(timeObject, format) string {{ dtLastDayOfPreviousMonthInFormat timeObject “2006/02/01” }}
dtLastDayOfCurrentMonthInFormat Datetime manipulation in format, returns string dtLastDayOfCurrentMonthInFormat(timeObject, format) string {{ dtLastDayOfCurrentMonthInFormat timeObject “2006/02/01” }}
dtLastDayOfNextMonthInFormat Datetime manipulation in format, returns string dtLastDayOfNextMonthInFormat(timeObject, format) string {{ dtLastDayOfNextMonthInFormat timeObject “2006/02/01” }}
dtFirstDayOfPreviousYearInFormat Datetime manipulation in format, returns string dtFirstDayOfPreviousYearInFormat(timeObject, format) string {{ dtFirstDayOfPreviousYearInFormat timeObject “2006/02/01” }}
dtFirstDayOfCurrentYearInFormat Datetime manipulation in format, returns string dtFirstDayOfCurrentYearInFormat(timeObject, format) string {{ dtFirstDayOfCurrentYearInFormat timeObject “2006/02/01” }}
dtFirstDayOfNextYearInFormat Datetime manipulation in format, returns string dtFirstDayOfNextYearInFormat(timeObject, format) string {{ dtFirstDayOfNextYearInFormat timeObject “2006/02/01” }}
dtLastDayOfPreviousYearInFormat Datetime manipulation in format, returns string dtLastDayOfPreviousYearInFormat(timeObject, format) string {{ dtLastDayOfPreviousYearInFormat timeObject “2006/02/01” }}
dtLastDayOfCurrentYearInFormat Datetime manipulation in format, returns string dtLastDayOfCurrentYearInFormat(timeObject, format) string {{ dtLastDayOfCurrentYearInFormat timeObject “2006/02/01” }}
dtLastDayOfNextYearInFormat Datetime manipulation in format, returns string dtLastDayOfNextYearInFormat(timeObject, format) string {{ dtLastDayOfNextYearInFormat timeObject “2006/02/01” }}
dtFuture Datetime manipulation to get the nearest future quarter, half or full hour dtFuture(timeObject, type) timeObject {{ dtFuture timeObject “quarter” }}
dtStartOfDay Datetime manipulation to get the start of the day time object dtStartOfDay(timeObject) timeObject {{ dtStartOfDay timeObject }}
dtEndOfDay Datetime manipulation to get the end of the day time object dtEndOfDay(timeObject) timeObject {{ dtEndOfDay timeObject }}
dtNearestWeekday returns nearest weekday of the timeObject. true - calculates in feature, otherwise in past dtNearestWeekday(timeObject, weekday, false?) timeObject {{ dtNearestWeekday timeObject, “Monday” }}
convertTimeUnits Converts one time unit to another. Possible units: s, m, h. convertTimeUnits(amount, from, to) float64 {{ convertTimeUnits 5 “h” “s” }}
parseDuration Parses text formated duration to the time.Duration. Accepts value in format 2h45m35.5s parseDuration(dur) time.Duration {{ parseDuration “245m” }}
parseDuration (roundTo) parseDuration could also receive optional roundTo setting, which is one of s, m and h parseDuration(dur, roundTo) time.Duration {{ parseDuration “245m35s” “m” }}
formatDuration Formats passed duration to the specified format. Receives time.Duration or string types (check syntax) formatDuration(dur, format) string {{ formatDuration “245m” “05 sec” }}
formatDuration (roundTo) formatDuration with optional roundTo param, which is one of s, m and h formatDuration(dur, format, roundTo) string {{ formatDuration “245m22.6s” “05 sec” “s” }}
Unix Its possible to get the unix value on any timeObject timeObject.Unix {{ $timeObject.Unix }}

Example when using current accounts time zone.

{{ $timeZone :=.Data.ErplyApi.ConfigurationList.timezone | toString }}
{{ unixToDate 1683201802 $timeZone "2006-02-01" }}
{{ formatDate "2022-11-11" "2006-01-02" "2006/02/01" $timeZone }}

Examples using dt functions:

<!-- DT date manipulations -->

<p>
  <!-- Get a usable date object -->
  <!-- Basic current server time (UTC) -->
  Server current time: {{ dtCurrent }}
</p>
<p>
  <!-- Get current time in a specific timezone / location -->
  <!-- #1 parameter here is the tz timezone identifier value
  get a reference for the available values in https://en.wikipedia.org/wiki/List_of_tz_database_time_zones -->
  Current time in TZ: {{ dtCurrentIn "America/New_York" }}
</p>
<p>
  <!-- Use an input in any possible format from another source -->
  <!-- #1 parameter is the input date value -->
  <!-- #2 parameter is the input date format, use the https://gosamples.dev/date-time-format-cheatsheet/ to read on how the format works  -->
  <!-- #3 is the timezone tz identifier value of the output time -->
  Time conversion from another format: {{ dtFromDateTime "2023-06-06T15:12:12Z07:00"
  "2006-01-02T15:04:05Z07:00" "America/New_York" }}
</p>

<!-- Manipulate the value of the date-->

<!-- Reduce by 1 year -->
<p>Current time reduced by 1 year: {{ dtAdjustDate dtCurrent "year" -1 }}</p>
<!-- Add 1 year -->
<p>Current time plus 1 year: {{ dtAdjustDate dtCurrent "year" 1 }}</p>
<!-- Reduce by 1 month -->
<p>Current time reduced by 1 month: {{ dtAdjustDate dtCurrent "month" -1 }}</p>
<!-- Add 1 month -->
<p>Current time plus 1 month: {{ dtAdjustDate dtCurrent "month" 1 }}</p>
<!-- Reduce by 1 day -->
<p>Current time reduced by 1 day: {{ dtAdjustDate dtCurrent "day" -1 }}</p>
<!-- Add 1 day -->
<p>Current time plus 1 day: {{ dtAdjustDate dtCurrent "day" 1 }}</p>

<!-- Get specific values -->
<!-- First and last day of week -->
<!-- #1 value of one of the provided functions: dtCurrent, dtCurrentIn or dtFromDateTime -->
<!-- #2 boolean value - true if week start day is Sunday and false for Monday -->
<p>First day of week(monday): {{ dtFirstDayOfWeek dtCurrent false }}</p>
<p>First day of week(sunday): {{ dtFirstDayOfWeek dtCurrent true }}</p>
<p>Last day of week(monday): {{ dtLastDayOfWeek dtCurrent false }}</p>
<p>Last day of week(sunday): {{ dtLastDayOfWeek dtCurrent true }}</p>

<!-- First and last day of the month -->
<!-- #1 value of one of the provided functions: dtCurrent, dtCurrentIn or dtFromDateTime -->
<p>First day of month: {{ dtFirstDayOfMonth dtCurrent }}</p>
<p>Last day of month: {{ dtLastDayOfMonth dtCurrent }}</p>

<p>First day of next month: {{ dtAdjustDate dtCurrent "month" 1 | dtFirstDayOfMonth }}</p>
<p>First day of previous month: {{ dtAdjustDate dtCurrent "month" -1 | dtFirstDayOfMonth }}</p>

<!-- First and last day of the year -->
<!-- #1 value of one of the provided functions: dtCurrent, dtCurrentIn or dtFromDateTime -->
<p>First day of the year: {{ dtFirstDayOfYear dtCurrent }}</p>
<p>Last day of the year: {{ dtLastDayOfYear dtCurrent }}</p>

<p>First day of next year: {{ dtAdjustDate dtCurrent "year" 1 | dtFirstDayOfYear }}</p>
<p>Last day of previous year: {{ dtAdjustDate dtCurrent "year" -1 | dtLastDayOfYear }}</p>

<!-- Format the date to anything thats needed -->
<!-- #1 dt time object from any of the previous functions -->
<!-- #2 in what format you need to get the date time format, use https://gosamples.dev/date-time-format-cheatsheet/ as date format reference -->
<p>Date to UnixDate: {{ dtToFormat dtCurrent "Mon Jan _2 15:04:05 MST 2006" }}</p>
<p>Date to RFC822: {{ dtToFormat dtCurrent "02 Jan 06 15:04 MST" }}</p>
<p>Date to RFC1123: {{ dtToFormat dtCurrent "Mon, 02 Jan 2006 15:04:05 MST" }}</p>
<p>Date to RFC3339Nano: {{ dtToFormat dtCurrent "2006-01-02T15:04:05.999999999Z07:00" }}</p>
<p>Date only: {{ dtToFormat dtCurrent "2006-01-02" }}</p>
<p>Time only: {{ dtToFormat dtCurrent "15:04:05" }}</p>
<p>Custom: {{ dtToFormat dtCurrent "15:04:05 2006/01/02" }}</p>

<!-- Chain current time -> add 1 year -> first day of the year -> to my format -->
<!-- With a set variable -->
<p>
  {{ $firstDayOfNextYear := dtAdjustDate dtCurrent "year" 1 | dtFirstDayOfYear }}
  First day of next year in RFC822: {{ dtToFormat $firstDayOfNextYear "02 Jan 06 15:04 MST" }}
</p>

<!-- Use helper functions -->
<!-- #1 date data from the previous functions -->
<!-- #2 what format to concert to -->
<!-- Note that these functions alter the date by 1 depending if its first or last, so further adjustments to the input date here is not needed -->
<p>First day of pervious month: {{ dtFirstDayOfPreviousMonthInFormat dtCurrent "02 Jan 06 15:04 MST"
  }}</p>
<p>First day of current month:{{ dtFirstDayOfCurrentMonthInFormat dtCurrent "02 Jan 06 15:04 MST"
  }}</p>
<p>First day of next month:{{ dtFirstDayOfNextMonthInFormat dtCurrent "02 Jan 06 15:04 MST" }}</p>
<p>First day of pervious year:{{ dtFirstDayOfPreviousYearInFormat dtCurrent "02 Jan 06 15:04 MST"
  }}</p>
<p>First day of current year:{{ dtFirstDayOfCurrentYearInFormat dtCurrent "02 Jan 06 15:04 MST"
  }}</p>
<p>First day of next year:{{ dtFirstDayOfNextYearInFormat dtCurrent "02 Jan 06 15:04 MST" }}</p>

<p>Last day of pervious month: {{ dtLastDayOfPreviousMonthInFormat dtCurrent "02 Jan 06 15:04 MST"
  }}</p>
<p>Last day of current month:{{ dtLastDayOfCurrentMonthInFormat dtCurrent "02 Jan 06 15:04 MST"
  }}</p>
<p>Last day of next month:{{ dtLastDayOfNextMonthInFormat dtCurrent "02 Jan 06 15:04 MST" }}</p>
<p>Last day of pervious year:{{ dtLastDayOfPreviousYearInFormat dtCurrent "02 Jan 06 15:04 MST"
  }}</p>
<p>Last day of current year:{{ dtLastDayOfCurrentYearInFormat dtCurrent "02 Jan 06 15:04 MST" }}</p>
<p>Last day of next year:{{ dtLastDayOfNextYearInFormat dtCurrent "02 Jan 06 15:04 MST" }}</p>

<!-- DT future -->
<h2>Get nearest future quarter, half or full hour for a datetime</h2>

{{ $sample := dtFromDateTime "12:14" "03:04" "GMT" }}

<p>{{ dtToFormat (dtFuture $sample "quarter") "03:04" }}</p>
<p>{{ dtToFormat (dtFuture $sample "half") "03:04" }}</p>
<p>{{ dtToFormat (dtFuture $sample "full") "03:04" }}</p>

<!-- Start and end of the day -->
<p>{{ $timeZone := toString .Data.ErplyApi.ConfigurationList.timezone }}</p>
<p>{{ $today := dtCurrentIn $timeZone }}</p>

{{ $start := dtStartOfDay $today }}
{{ $end := dtEndOfDay $today }}

<!-- Get Unix on any timeObject (from any of the helpers that return that type) value -->
<p>{{ $start.Unix }}</p>
<p>{{ $end.Unix }}</p>

Types conversions

Name Description Usage Samples
toString Attempts to convert a type to a string. Can be used to make sure an interface value is always a string. toString(undefined) {{ toString 100 }}
toFloat Converts a string to float. Created value can be used on other helper functions. toFloat(string) {{ toFloat “100.23” }}
toInt Converts a string to int. Created value can be used on other helper functions. toInt(string) {{ toInt “100” }}
toBool Converts a string, int or float to boolean. Created value can be used on other helper functions. toBool(string) {{ toBool “1” }}
intToString Converts a int to string. Created value can be used on other helper functions. intToString(int) {{ intToString 100 }}
stringToUint32 Converts a string to int32. Created value can be used on other helper functions. stringToUint32(string) {{ stringToUint32 “100” }}
intToUint32 Converts a int to int32. Created value can be used on other helper functions. intToUint32(int) {{ intToUint32 100 }}
floatToString Converts a float to string. Created value can be used on other helper functions. floatToString(float64) {{ floatToString 100.5 }}
floatToInt Converts a float to int. Created value can be used on other helper functions. floatToString(float64) {{ floatToInt 100.5 }}
floatToEvenString Converts a float to int and returns as a string. Created value can be used on other helper functions. floatToEvenString(float64) {{ floatToEvenString 100.5 }}

Example where the data could be stored in a JS variable for js usage.

<script>
  (function () {
    const myData = JSON.parse({{ .Data.WMSApi.ProductPickingEfficiencyList | toJson}})
  })();
</script>

Constructors

Name Description Usage Samples
mkMap Creates map[string]string, parameters count must be even (2,4,etc), first is key and second - value mkMap(key, value, …) {{ m := mkMap “key” “val” “key2” “val2” }}
mkAnyMap Creates map[string]any, parameters count must be even (2,4,etc), first is key and second - value mkAnyMap(key, value, …) {{ m := mkAnyMap “key” “val” “key2” 2 }}
mkCtxMap Creates map[string]any, first parameter should be the template context (the dot), rest is the same as mkAnyMap. This function makes sure that everything in the context is still available when used as a passing function to pass data to partials. mkCtxMap(., key, value, …) {{ m := mkCtxMap . “key” “val” “key2” 2 }}
mkIntArray Creates array (slice) of integers, if parameters not passed then empty array created mkIntArray(1, 2, …) {{ m := mkIntArray 1 2 }}
mkStringArray Creates array (slice) of strings, if parameters not passed then empty array created mkStringArray(“foo”, “bar”, …) {{ m := mkStringArray “foo” “bar” }}

Math

Name Description Function arguments Usage
round Rounds the float value to nearest integer value round(myFloat) {{ round 100.456 }}
roundToEven Rounds to the nearest integer, rounding ties to even. roundToEven(myFloat) {{ round 100.456 }}
roundTo Round to the nearest requested precision point. roundTo(myFloat, decimalPlaces) {{ roundTo 100.456 2 }}
roundToAndHumanize Round to the nearest requested precision point and add comma separation for thousands. roundToAndHumanize(myFloat, decimalPlaces) {{ roundToAndHumanize 100.456 2 }}
roundToAndHumanizeWithConf Same as roundToAndHumanize, but with configuration options. E.g " ," will apply space to thousand separator and comma to decimal separator roundToAndHumanizeWithConf(myFloat, decimalPlaces, " ,") {{ roundToAndHumanizeWithConf 100.456 2 “,.” }}
roundAndFormatTo1f Round to 1 decimal. roundAndFormatTo1f(myFloat) {{ roundAndFormatTo1f 100.456 }}
roundAndFormatTo2f Round to 2 decimals. roundAndFormatTo2f(myFloat) {{ roundAndFormatTo2f 100.456 }}
roundAndFormatTo3f Round to 3 decimals. roundAndFormatTo3f(myFloat) {{ roundAndFormatTo3f 100.456 }}
roundAndFormatTo4f Round to 4 decimals. roundAndFormatTo4f(myFloat) {{ roundAndFormatTo4f 100.456 }}
toAbsolute Convert to absolute value toAbsolute(myValue) {{ toAbsolute -100.456 }}
removeZeroes Remove trailing zeroes. Example: 100.0500 -> 100.05 removeZeroes(myFloat) {{ removeZeroes -100.4560000 }}
humanize Add comma separation to thousands. Example: 100000.00 -> 100,000.00 humanize(myFloat) {{ humanize 100.456 }}
humanizeWithConf Same as humanize, but with configuration options. E.g " ," will apply space to thousand separator and comma to decimal separator humanizeWithConf(myFloat, decimals, " ,") {{ humanizeWithConf 100.456 2 “,.” }}
add Adds all the input parameters. Can define as many parameters as needed. add(myVal1, myVal2, …) {{ add -100.4560000 1 3 }}
subtract Subtracts the input parameters from 0. Can define as many parameters as needed. subtract(myVal1, myVal2, …) {{ subtract -100.4560000 1 3 }}
subtractFrom Subtracts the input parameters from specified value. Can define as many parameters as needed. subtractFrom(initialVal, myVal1, myVal2, …) {{ subtractFrom -100.4560000 1 3 }}
divide Divides the input parameters. Can define as many parameters as needed. Note that 0 values are ignored. divide(myVal1, myVal2, …) {{ divide -50 1 }}
div Divide 2 exact values div(val1, val2) {{ div -50 1 }}
multiply Multiplies the input parameters. Can define as many parameters as needed. Note that 0 values are ignored. multiply(myVal1, myVal2, …) {{ multiply -50 1 }}
mul Multiply 2 exact values mul(val1, val2) {{ mul -50 1 }}
pow Calculates the parameter 1 to the power parameter 2 power pow(myFloat1, myFloat2) {{ pow 1.1 1.2 }}
ceil Round a floating point value up to the nearest integer ceil(myFloat1) {{ ceil 1.1 }}
floor Returns the greatest integer value less than or equal to x. floor(myFloat1) {{ floor 1.1 }}

As with the functions that accept a single parameter the same applies here that they can also be used with the pipe notation.

{{ 13.6 | roundToEven }}
{{ 13.6 | round }}

Maps, lists and arrays

Name Description Definition Samples
getListTotal Gets the total value of the requested list column. getListTotal(myListData, myColumn) {{ getListTotal .Data.WMSApi.InboundEfficiencyList “Duration” }}
getRoundedListTotal Gets the total value of the requested list column. Applies the roundTo logic. getRoundedListTotal(myListData, myColumn, decimals) {{ getRoundedListTotal .Data.WMSApi.InboundEfficiencyList “Duration” 2 }}
getRoundedAndHumanizedListTotal Same as getRoundedListTotal. Applies humanization (thousands comma separation) logic. getRoundedAndHumanizedListTotal(myListData, myColumn, decimals) {{ getRoundedAndHumanizedListTotal .Data.WMSApi.InboundEfficiencyList “Duration” 2 }}
isInStringArray Checks if element exists in array of strings. isInStringArray(“el”, strSlice) {{ isInStringArray “el” someStringArray }}
isInIntArray Checks if element exists in array of ints. isInIntArray(2, intSlice) {{ isInIntArray 2 someIntArray }}
indexOfStringSlice Returns index of element from array of strings. 0 if not found. indexOfStringSlice(strSlice, “el”) {{ indexOfStringSlice someStringArray “el” }}
addToIntArray Appends element to the array of integers ([]int). addToIntArray(intSlice, 2) {{ addToIntArray intArray 2 }}
addToStringArray Appends element to the array of strings ([]string). addToStringArray(strSlice, “el”) {{ addToStringArray stringArray “el” }}
arrayToString Converts an array of any type to string having elements separated by delim. string array elements must not contain spaces arrayToString(strSlice, “,”) string {{ arrayToString array “,” }}
setAnyMapValue Sets key-value entry to the map, supports any type. setAnyMapValue(map[string]any, string, any) map[string]any {{ setAnyMapValue $map “foo” 2 }}
in Helper function imitating regular loop for i:=0; i<10; i++. in(from, to) {{ range $i := in 0 10 }}

{{ $i }}

{{ end }}
inZeroPadding Same as in, but fills zeroes for smaller number sizes. E.g. in(from, to) {{ range $i := in 0 10 }}

{{ $i }}

{{ end }}
reverseStringArray Reverses string array ["one", "two"] => ["two", "one"] reverseStringArray(myStringArray) {{ reverseStringArray $array }}
getYearRange Similar to in but the last adjustment is done against the current year getYearRange(from, adjustCurrentYear) {{ range getYearRange 1800 10 }}
inZeroPadding Generate a range of string with given amount of zero paddings inZeroPadding(from, to, numberOfPads) {{ range inZeroPadding 1 12 2 }}
getSortedKeys Extracts keys from map then sorts them based on the passed order (asc or desc) and returns keys as []string getSortedKeys(map[string]any, “desc”) {{ getSortedKeys $m “desc” }}

Get totals notes

Note that getListTotal, getRoundedListTotal and getRoundedAndHumanizedListTotal functions under the hood return the value as a string. This means if you intend to use the value for further processing using the same helper functions then you would need to convert the values to required types first.

Example:

{{ $val := getRoundedListTotal .Data.WMSApi.InboundEfficiencyList "OpenTimestamp" 2 }}
{{ $val := toFloat $val }}
{{ $val := add $val 15.15756 }}
{{ roundToAndHumanize $val 2 }}

Also note that the function can be used with any integrated lists that contain an integer or float column.

Working with JSON

This section contains all json related manipulations, using helper functions, gjson.Result object and modifier functions that could be used during path assembly for the gjson.Result.Get calls.

Name Description Usage Samples
toJson Attempts to convert a type to valid json. Can be used on list types or entities to get the structure for JS usage. toJson(data) string {{ toJson .Data.WMSApi.InboundEfficiencyList }}
jsonLookup Looking json value by path. May return different types: int, string, etc… If under path json, returns map[string]any jsonLookup(jsonStr, path) any {{ jsonLookup `{“foo”:“bar”}` “foo” }}
jsonLookupRaw Looking json value by path. Always returns string. If under path json, returns stringified json JsonLookupRaw(jsonStr, path) string {{ JsonLookupRaw `{“foo”:“bar”}` “foo” }}
jsonType Returns json type for path. Values: “Null”, “Number”, “String”, “JSON”, “Boolean” JsonType(jsonStr, path) string {{ JsonType `{“foo”:“bar”}` “foo” }}
jsonArrayLen Returns length of json array. Returns 0 if under path is object JsonArrayLen(jsonStr, path) int {{ JsonArrayLen [] "" }}
jsonObjKeys Returns all keys of json object under path. JsonObjKeys(jsonStr, path) int {{ JsonObjKeys `{“foo”:1,“bar”:2}` "" }}
jsonResult Returns JSON Result object containing many valuable functions and fields. More details jsonResult(jsonStr, path) gjson.Result {{ jsonResult `{“foo”:1,“bar”:2}` “foo” }}
jsonPretty Takes in string or []byte and returns beautified json jsonPretty(json) string {{ jsonPretty `{“foo”:1,“bar”:2}` }}
jsonSet Adds values to and existing json structure jsonSet(json, path, val) string {{ jsonSet `{“foo”: 1}` “bar” 2 }}
jsonSetObj Adds an entire raw json string object or array structure jsonSetObj(json, path, val) string {{ jsonSetObj `{“foo”: 1}` “bar” `{“someObject”: “test”}` }}
jsonDel Remove values from an existing json structure jsonDel(json, path) string {{ jsonDel `{“foo”: 1, “bar: 2}` “bar” }}

Samples

JSON sample payload

{
  "name": {
    "first": "Tom",
    "last": "Anderson"
  },
  "age": 37,
  "children": [
    "Sara",
    "Alex",
    "Jack"
  ],
  "emptyArray": [],
  "fav.movie": "Deer Hunter",
  "friends": [
    {
      "first": "Dale",
      "last": "Murphy",
      "age": 44,
      "nets": [
        "ig",
        "fb",
        "tw"
      ]
    },
    {
      "first": "Roger",
      "last": "Craig",
      "age": 68,
      "nets": [
        "fb",
        "tw"
      ]
    },
    {
      "first": "Jane",
      "last": "Murphy",
      "age": 47,
      "nets": [
        "ig",
        "tw"
      ]
    }
  ]
}

Function usage examples

<div>
  {{ $jsonStr := `{"name": {"first": "Tom", "last": "Anderson"},"age":37,"children":
  ["Sara","Alex","Jack"],"emptyArray": [],"fav.movie": "Deer Hunter","friends": [{"first": "Dale",
  "last": "Murphy", "age": 44, "nets": ["ig", "fb", "tw"]},{"first": "Roger", "last": "Craig",
  "age": 68, "nets": ["fb", "tw"]},{"first": "Jane", "last": "Murphy", "age": 47, "nets": ["ig",
  "tw"]}]}`}}

  <p>Get value: <code>{{ jsonLookup $jsonStr "age" }}</code></p>
  <!-- 37 -->
  <p>Get value map: <code>{{ jsonLookup $jsonStr "name" }}</code></p>
  <!-- map[first:Tom last:Anderson] -->
  <p>Get value as string: <code>{{ jsonLookupRaw $jsonStr "age" }}</code></p> <
  !-- "37" -->
  <p>Get obj as string: <code>{{ jsonLookupRaw $jsonStr "name" }}</code></p>
  <!-- {"first": "Tom", "last": "Anderson"} -->
  <p>Get json type: <code>{{ jsonType $jsonStr "name" }}</code></p>
  <!-- JSON -->
  <p>Get json type: <code>{{ jsonType $jsonStr "age" }}</code></p>
  <!-- Number -->
  <p>Get json type: <code>{{ jsonType $jsonStr "children" }}</code></p>
  <!-- JSON -->
  <p>Get json type: <code>{{ jsonType $jsonStr "not_exist" }}</code></p>
  <!-- NULL -->
  <p>Json array length: <code>{{ jsonArrayLen $jsonStr "children" }}</code></p>
  <!-- 3 -->
  <p>Json array length (object): <code>{{ jsonArrayLen $jsonStr "name" }}</code></p>
  <!-- 0 -->
  <p>Json object keys root: <code>{{ jsonObjKeys $jsonStr "" }}</code></p>
  <!-- [name age children emptyArray fav.movie friends] -->
  <p>Json object keys path: <code>{{ jsonObjKeys $jsonStr "name" }}</code></p>
  <!-- [first last] -->
  <p>Json object keys array: <code>{{ jsonObjKeys $jsonStr "children" }}</code></p>
  <!-- [] -->
</div>

JSON Result object

GOERP uses library gjson to read and process json at specific path. Helper function jsonResult returns gjson.Result object which contains many valuable fields and functions for json processing. All those functions and fields may significantly simplify work with json inside templates.

Fields

Name Description Usage Samples
Type Type is the json type (Null, False, Number, String, True, JSON) Result.Type.String() string {{ $result.Type }}
Raw Raw is the raw json Result.Raw string {{ $result.Raw }}
Index Index of raw value in original json, zero means index unknown Result.Index int {{ $result.Index }}
Indexes Indexes of all the elements that match on a path containing the ‘#’ query character Result.Indexes []int {{ $result.Indexes }}

Functions

Name Description Usage Samples
String Returns a string representation of the value String() string {{ $result.String }}
Bool Returns a boolean representation of the value Bool() bool {{ $result.Bool }}
Int Returns a integer representation of the value Int() int64 {{ $result.Int }}
Uint Returns a unsigned integer representation of the value Uint() uint64 {{ $result.Uint }}
Float Returns a float representation of the value Float() float64 {{ $result.Float }}
Time Returns a time.Time representation of the value Time() time.Time {{ $result.Time }}
Array Returns array of elements as Result objects Array() []Result {{ $result.Array }}
IsObject Returns true if result is a json object IsObject() bool {{ if $result.IsObject }} {{ end }}
IsArray Returns true if result is a json array IsArray() bool {{ if $result.IsArray }} {{ end }}
IsBool Returns true if result is a json boolean IsBool() bool {{ if $result.IsBool }} {{ end }}
Map Returns map of nested results. root Result must be json object Map() map[string]Result {{ $result.Map }}
Get Searches result for the specified path. Check queries guide for more info and playground Get(path string) Result {{ $result.Get $path }}
Exists Returns true if json value exists Exists() bool {{ if $result.Exists }} {{ end }}
Value Returns value of related type (int, string, etc.), map[string]any for json objects and []any for arrays Value() any {{ $result.Value }}
Less Return true if a token is less than another token. Null < False < Number < String < True < JSON Less(token Result, caseSensitive bool) bool {{ $result.Less $result2 false }}
Paths Paths returns the original GJSON paths for a Result Paths(json string) []string {{ $result.Paths $entireJson }}
Path Paths returns the original GJSON path for a Result Path(json string) string {{ $result.Path $entireJson }}

Modifier functions

Modifier functions could be used in paths for the gjson.Result. They always starts with @ (e.g. @sum) and may be chained using | (e.g. @sum:2|@suffix:$). Also, some modifiers may accept additional arguments that could be passed through : (e.g. @sum:2, which is decimals in this case).

Please note, $r in samples is the gjson.Result object.

Name Description Usage Samples
commaSepStr Converts json array to comma separated string. null, {}s and []s would be skipped. When working with numbers, pass int as an argument “@commaSepStr:arg” {{ $r.Get “@commaSepStr” }}
arrToStr Same as commaSepStr, but allows to define the separator through arguments. “@arrToStr:arg” {{ $r.Get “@arrToStr:;” }}
prefix Sets prefix to the value “@prefix:arg” {{ $r.Get “@prefix:pref_” }}
suffix Sets suffix to the value “@suffix:arg” {{ $r.Get “@suffix:_suf” }}
getOldestItemDate Automation specific. Returns oldest record from items array. Arg: format of output date “@getOldestItemDate:arg” {{ $r.Get “@getOldestItemDate:2006-01-02T15:04:05Z” }}
unique Removes duplicates from the json array “@unique” {{ $r.Get “@unique” }}
notNull Removes nulls from the json array “@notNull” {{ $r.Get “@notNull” }}
sum Sums up all values in json array, stringified numbers are valid, other types are ignored. Define decimals through arg “@sum:arg” {{ $r.Get “@sum:2” }}
min Extracts minimum number from json array, same restrictions as in sum “@min” {{ $r.Get “@min” }}
max Extracts maximum number from json array, same restrictions as in sum “@max” {{ $r.Get “@max” }}
skip Allows to skip value (returns empty value) based on conditions: Supported args: zero, eq,val, neq,val, gt,val, lt,val “@skip:arg” {{ $r.Get “@skip:eq,John” }}

Working with XML

All XML content converted to the JSON when received from the API. And JSON body is converted to the XML when sending to the API. This allows to work with XML content in the same way as with JSON, using all available options like chaining, generating, etc. Although, because XML cannot be fully represented as a JSON structure, some additional rules must be followed while assembling or reading XML payload through JSON.

Special rules

Use the following rules whenever reading the XML Response or constructing the XML request.

  • All tag attributes are represented as a separate key with the - prefix. For example, the XML <tag attr="value"></tag> would be represented as {"tag": {"-attr": "value"}}.
  • If tag contains attributes and text, the text would be represented as a separate field with the #text name. For example, the XML <tag attr="value">content</tag> would be represented as {"tag": {"-attr": "value", "#text": "content"}}.
  • <?xml version="1.0" encoding="UTF-8"?> header added automatically to the XML request before sending it to the API.

XML payload in JSON sample

XML

<?xml version="1.0" encoding="UTF-8"?>
<bookstore xmlns:p="urn:schemas-books-com:prices">

  <book category="COOKING">
    <title lang="en">Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <p:price>30.00</p:price>
  </book>

  <book category="CHILDREN">
    <title lang="en">Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <p:price>29.99</p:price>
  </book>

  <book category="WEB">
    <title lang="en">XQuery Kick Start</title>
    <author>James McGovern</author>
    <author>Per Bothner</author>
    <author>Kurt Cagle</author>
    <author>James Linn</author>
    <author>Vaidyanathan Nagarajan</author>
    <year>2003</year>
    <p:price>49.99</p:price>
  </book>

  <book category="WEB">
    <title lang="en">Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <p:price>39.95</p:price>
  </book>

</bookstore>

JSON generated from XML

{
  "bookstore": {
    "-xmlns:p": "urn:schemas-books-com:prices",
    "book": [
      {
        "-category": "COOKING",
        "author": "Giada De Laurentiis",
        "p:price": "30.00",
        "title": {
          "#text": "Everyday Italian",
          "-lang": "en"
        },
        "year": "2005"
      },
      {
        "-category": "CHILDREN",
        "author": "J K. Rowling",
        "p:price": "29.99",
        "title": {
          "#text": "Harry Potter",
          "-lang": "en"
        },
        "year": "2005"
      },
      {
        "-category": "WEB",
        "author": [
          "James McGovern",
          "Per Bothner",
          "Kurt Cagle",
          "James Linn",
          "Vaidyanathan Nagarajan"
        ],
        "p:price": "49.99",
        "title": {
          "#text": "XQuery Kick Start",
          "-lang": "en"
        },
        "year": "2003"
      },
      {
        "-category": "WEB",
        "author": "Erik T. Ray",
        "p:price": "39.95",
        "title": {
          "#text": "Learning XML",
          "-lang": "en"
        },
        "year": "2003"
      }
    ]
  }
}

Simple example of sending and reading XML

{{ template "pg-layout" . }}

{{ define "body" }}

<form method="post">
    <input type="hidden" name="CustomApi.Api.Post.soapReq" value="https://www.dataaccess.com/webservicesserver/NumberConversion.wso">
    <input type="hidden" name="CustomApi.Api.Header.soapReq.Content-Type" value="text/xml; charset=utf-8">
    <input type="hidden" name="CustomApi.Api.Xml.soapReq.string.soap:Envelope.-xmlns:soap" value="http://schemas.xmlsoap.org/soap/envelope/">
    <input type="hidden" name="CustomApi.Api.Xml.soapReq.stirng.soap:Envelope.soap:Body.NumberToWords.-xmlns" value="http://www.dataaccess.com/webservicesserver/">
    <input type="text" name="CustomApi.Api.Xml.soapReq.string.soap:Envelope.soap:Body.NumberToWords.ubiNum" value="">

    <button type="submit">Send</button>
</form>

<h2>Sent:</h2>
<pre>{{ .Data.CustomApi.Api.Requests.soapReq.Xml.Raw | jsonPretty }}</pre>

<h2>Received:</h2>
<pre>{{ .Data.CustomApi.Api.Requests.soapReq.Response.Raw | jsonPretty }}</pre>

Requested number as text: 
<b>{{ .Data.CustomApi.Api.Requests.soapReq.Response.Get "Envelope.soap:Body.NumberToWordsResponse.m:NumberToWordsResult" }}</b>

{{ end }}

If conditions

If conditions can be used in the templates

{{ if true }}
    <h1>True</h1>
{{ else }}
    <h1>False</h1>
{{ end }}

Note that if condition comparison is type sensitive. If invalid types (types that cannot be compared) are given the template parser will break from that point onward.

Should always make sure that the types are comparable or cast them to comparable types before the condition check

<!-- Invalid, template will break from this point  -->
{{ if gt 1 "2" }}
{{ end }}

<!-- Valid -->
{{ if g1 1 (toInt "2") }}
{{ end }}

<!-- Valid, type cast from dynamic api result -->
{{ if g1 1 ($dynRes.Get "id").Int }}
{{ end }}

Available operators

  • eq - boolean truth of arg1 == arg2
  • ne - boolean truth of arg1 != arg2
  • lt - boolean truth of arg1 < arg2
  • le - boolean truth of arg1 <= arg2
  • gt - boolean truth of arg1 > arg2
  • ge - boolean truth of arg1 >= arg2
  • md - boolean truth of arg1 % arg2

Multiple conditions

Multiple conditions can also be described. There can be any number of conditions.

{{ if and (condition1) (condition2) }}
{{ end }}

For this we can use and & or. Use “()” to separate arguments.

{{ if and (or (condition1) (condition2)) (condition2) }}
{{ end }}

Sample

{{ if and (eq 1 2) (ne 3 4) }}
{{ end }}

Tools helper

Tools is a special helper that has more powerful access to the contents of the context.

Generates a full path link to the source static file. Makes sure the link does not break if the site is moved to a custom domain or if the link contains custom path parameters.

This is a replacement for the older staticFileLink and takes care multiple shortcoming of the original.

<script src="{{ .Tools.StaticLink " AAA-Etag-js" }}"></script>

IsPath

Checks if we are currently navigating to the given custom path. Counts all 3 custom paths.

{{ .Tools.IsPath "path1" }}
{{ .Tools.IsPath "path1/path2" }}
{{ .Tools.IsPath "path1/path2/path3" }}

Also used for automatic sourcemap importing for sub-paths.

GetNavPath

Generates a valid link path that composes of the current client code, language and the given path value. Counts in possible navigation differences from custom domains.

{{ .Tools.GetNavPath "da-csv-export" }}

This would generate the correct paths according to the current handler

/104146/en/da-csv-export <!-- regular -->
/public/104146/en/da-csv-export?some=value <!-- public -->
/en/da-csv-export?some=value <!-- custom domain -->
Info

Optional language parameter is available from version 1.215+

{{ .Tools.GetNavPath "da-csv-export" "fi" }}
/104146/fi/da-csv-export <!-- regular -->
/public/104146/fi/da-csv-export?some=value <!-- public -->
/fi/da-csv-export?some=value <!-- custom domain -->

Browser

A separate function to parse data from the user agent header to specific data points. Can be used to determine if dealing with a mobile device or attempt to identify the platform used.

Browser

{{ .Browser.Name }}
{{ .Browser.Version }}
{{ .Browser.ShortVersion }}

Device

{{ .Browser.Device.IsConsole }}
{{ .Browser.Device.IsMobile }}
{{ .Browser.Device.IsTablet }}

Platform

{{ .Browser.Platform.Name }}
{{ .Browser.Platform.Version }}

Bot

{{ .Browser.Bot.Name }}
{{ .Browser.Bot.IsBot }}
{{ .Browser.Bot.Why }}

ExecTemplate

Executes template that can be assigned to the variable and could be passed to other data points (e.g. email body).

First of all we need to have template with payload:

{{ define "pg-in-build-template-parser-partial" }}

<h2>Hello, {{ .Session.ClientCode }}</h2>

<div align="left">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut
    labore et dolore magna aliqua.
</div>
<div align="right">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut
    labore et dolore magna aliqua.
</div>
<div align="center">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut
    labore et dolore magna aliqua.
</div>
<div align="justify">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut
    labore et dolore magna aliqua.
</div>

<h2>Using API calls inside executed template</h2>

{{ $warehouses := .Data.AccountAdminApi.Api.Requests.getWarehouses.Response.Get "data.warehouses" }}

<ul>
    {{ range $w := $warehouses.Array }}
    <li>{{ $w.Get "id" }}</li>
    {{ end }}
</ul>

{{ end }}

Then we can execute that template on other page and use resulting content wherever needed:

{{ template "pg-layout" . }}

{{ define "body" }}

<input type="hidden" name="AccountAdminApi.Api.Get.getWarehouses" value="v1/warehouse" data-preset-val="v1/warehouse" />
<input type="hidden" name="ErplyApi.Api.Post.getProducts" value="getProducts" data-preset-val="getProducts" />
<input type="hidden" name="ErplyApi.Api.PostParam.getProducts.getStockInfo" value="1" data-preset-val="1" />

<h1>Executing template from page...</h1>

<!-- We can pass any data to the function, like we do with regular partials inside templates -->
{{ $result := .Tools.ExecTemplate "pg-in-build-template-parser-partial" (.) }}
<pre>{{ $result }}</pre>

And result would be:

<h2>Hello, 104670</h2>

<div align="left">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut
    labore et dolore magna aliqua.
</div>
<div align="right">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut
    labore et dolore magna aliqua.
</div>
<div align="center">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut
    labore et dolore magna aliqua.
</div>
<div align="justify">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut
    labore et dolore magna aliqua.
</div>

<h2>Using API calls inside executed template</h2>

<ul>
    <li>1</li>
    <li>3</li>
    <li>4</li>
    <li>10</li>
    <li>11</li>
    <li>12</li>
    <li>13</li>
</ul>

CSP

Used to set server generated nonce to script and styles. When added correctly then the console error messages should no longer appear.

Link sources

<link rel="stylesheet" {{ .Tools.CSP }} href="{{ .Tools.StaticLink "Test-css" }}">
<script {{ .Tools.CSP }} src="{{ .Tools.StaticLink "add-billing-statement-js" }}"></script>

Inline

<head>
    <style {{ .Tools.CSP }}>
        .color-red {
            color: red;
        }
    </style>
</head>

<script {{ .Tools.CSP }}>
    console.log("test");
</script>

B2bAuthDomain (b2b specific)

While using Automat API to make b2b authentication calls, we need to pass the domain which is available only in the template (and we don’t have connection with template in the API calls). To get the current domain we can use .Tools.B2bAuthDomain and pass it to the necessary field.

<input type="hidden" name="AutomatApi.Api.Post.register" value="v1/b2b/register-user">
<input type="hidden" name="AutomatApi.Api.Json.register.string.domain" value="{{ .Tools.B2bAuthDomain }}">

IsModuleConfigured

Used to check if a specific module is currently enabled.

Note that this check is always checking against the current application (from the currently rendered template), so if the uuid being checked is a module for another app then it will always return false for it.

As a parameter give the uuid of the module you want to check. Returns a boolean value.

{{ .Tools.IsModuleConfigured "0cea1a50-5462-4fbc-9160-20ba082ec2be" }}

We can then generate some logic based on its result

{{ if .Tools.IsModuleConfigured "0cea1a50-5462-4fbc-9160-20ba082ec2be" }}
    <p>Extra features enabled</p>
{{ else }}
    <p>Extra features disabled</p>
{{ end }}

GetEnabledModules

Can be used to read a list of currently enabled modules.

Note that this check is always checking against the current application (from the currently rendered template), so it will not return uuid’s for modules that have been enabled for other applications.

Returns a comma separated list(string) of uuid’s.

{{ .Tools.GetEnabledModules }}
<!-- = uuid1,uuid2 -->

We can explode the result with split when we need to create a list out of it.

<ul>
{{ range (split .Tools.GetEnabledModules ",") }}
    <li>{{ . }}</li>
{{ end }}
</ul>

JWT

Basic helpers to sign and verify jwt tokens.

Create / Sign

Use the sign function to create a simple jwt token.

Parameters

  1. Claims / payload. Can be either an object, map or a json string.
{{ $myToken1 := sign `{"foo": "bar"}` "my-secret" "HS256" 1200 }}
{{ $myToken2 := sign (mkAnyMap "foo" "bar") "my-secret" "HS256" 1200 }}
  1. Secret to sign. Can be pulled from either variables or other sources that do not expose it to the html (api, cache).
<!-- Can be a string however the value is exposed in the html -->
{{ $claims := mkAnyMap "foo" "bar" }}
{{ $myToken := sign $claims "my-secret" "HS256" 1200 }}
<!-- Reading it from the api will hide the secret from parsed content -->
<input type="hidden" name="CaFaApi.Api.Get.myRequest1" value="v3/configuration" data-preset-val="v3/configuration">
<input type="hidden" name="CaFaApi.Api.Path.myRequest1.id" value="37" data-preset-val="37">
{{ $secret := (.Data.CaFaApi.Api.Requests.myRequest1.Response.Get "value").String }}

{{ $claims := mkAnyMap "foo" "bar" }}
{{ $myToken := sign $claims $secret "HS256" 1200 }}
<!-- Reading from variables is also hidden -->
{{ $claims := mkAnyMap "test" "val"}}
{{ $myToken := sign $claims (.Variables.Get "jwt.secret").String "HS256" 1200 }}
  1. Algorithm, currently allowed values are: HS256, HS512, RS256 and RS512.
  2. Expiration that will be added as the exp claim. Value is in seconds.

Verify

Verify the token against the key and expiration

When successful the result claims is a json result object where we can use the same Get fetching functionality as we use in dynamic api responses.

{{ $claims := verify $myToken "my-secret" }}
{{ $expVal := ($claims.Get "exp").Int }}

Error returned in content

If the validation fails the result will be returned as an error in the claims result.

{{ $claims := verify $myToken "my-secret" }}
<!-- {"error": "some failure reason"} -->

Fail template parse

If the validation fails then server returns the general error response screen.

{{ $claims := verifyWithFailure $myToken "my-secret" }}