Skip to Content
DocsPrompt EditorVariables & Templates

Variables & Templates

Variables transform static prompts into dynamic, reusable templates. LLMx Prompt Studio uses the N8N template syntax with over 60 built-in helper functions for powerful data manipulation.

Basic Syntax

Variable References

Use double curly braces to reference variables:

Hello, {{ name }}! Welcome to {{ company_name }}.

When rendered with { name: "Alice", company_name: "Acme Corp" }:

Hello, Alice! Welcome to Acme Corp.

Alternative Syntax

Access variables via the $var container:

Hello, {{ $var.name }}!

Both syntaxes are equivalent.

Defining Variables

In the Metadata Panel

  1. Open the Metadata panel (Tag icon in header)
  2. Click Add Variable in the Variables section
  3. Configure the variable:
FieldDescription
NameVariable identifier (no spaces, hyphens)
TypeData type (string, number, boolean, array, object)
Default ValueFallback when no value provided
DescriptionDocumentation for team members
RequiredWhether a value must be provided

Variable Types

TypeExample DefaultUse Case
string"Hello"Text content
number42Counts, prices, IDs
booleantrueFeature flags, conditions
array["a", "b"]Lists, options
object{"key": "value"}Structured data

Quick Insert Variables

There are multiple ways to quickly insert variable references:

  1. Type /var in the editor
  2. Press Enter to open the Variable Picker
  3. Search or browse defined variables
  4. Select to insert {{ $var.variableName }} at cursor position

You can also type /var followed by text to filter variables directly in the autocomplete menu (e.g., /var user shows all variables with “user” in the name).

Using Keyboard Shortcut

  1. Press Cmd + Shift + I (Mac) or Ctrl + Shift + I (Windows)
  2. The Variables tab is shown by default
  3. Search or browse available variables
  4. Select to insert at cursor position

Using Autocomplete

Type {{ and the editor shows autocomplete suggestions for all defined variables (including inherited ones from parent folders).

Expressions

Property Access

Access nested properties with dot notation:

{{ user.profile.email }} {{ customer.address.city }}

Array Indexing

Access array elements by index:

{{ items[0].name }} {{ colors[2] }}

Arithmetic

Perform calculations:

Total: {{ price * quantity }} With tax: {{ price * 1.08 }} Discounted: {{ originalPrice - discount }}

Conditional (Ternary)

Use ternary operators for conditional content:

{{ age >= 18 ? 'adult' : 'minor' }} {{ items.length > 0 ? 'You have items' : 'Cart is empty' }} {{ isPremium ? 'Welcome, Premium member!' : 'Upgrade to Premium' }}

Built-in Variables

These variables are always available:

VariableDescriptionExample Value
$nowCurrent timestamp (ms)1703520000000
$todayToday’s date (ISO)"2024-12-25"
$timestampFull ISO timestamp"2024-12-25T10:30:00.000Z"

Helper Functions Reference

Helper functions start with $ and provide powerful data transformations.

String Manipulation

FunctionDescriptionExample
$uppercase(str)Convert to uppercase{{ $uppercase(name) }}"ALICE"
$lowercase(str)Convert to lowercase{{ $lowercase(name) }}"alice"
$trim(str)Remove whitespace from edges{{ $trim(" hello ") }}"hello"
$trimStart(str)Remove leading whitespace{{ $trimStart(" hi") }}"hi"
$trimEnd(str)Remove trailing whitespace{{ $trimEnd("hi ") }}"hi"
$length(str)Get string length{{ $length(name) }}5
$substring(str, start, end)Extract substring{{ $substring("hello", 0, 3) }}"hel"
$slice(str, start, end)Extract portion{{ $slice("hello", -2) }}"lo"
$replace(str, search, replace)Replace first match{{ $replace("hello", "l", "x") }}"hexlo"
$replaceAll(str, search, replace)Replace all matches{{ $replaceAll("hello", "l", "x") }}"hexxo"
$split(str, separator)Split into array{{ $split("a,b,c", ",") }}["a","b","c"]
$join(arr, separator)Join array to string{{ $join(items, ", ") }}"a, b, c"
$concat(...args)Concatenate strings{{ $concat("Hello", " ", name) }}"Hello Alice"

String Checks

FunctionDescriptionExample
$startsWith(str, search)Check prefix{{ $startsWith(email, "admin") }}
$endsWith(str, search)Check suffix{{ $endsWith(file, ".pdf") }}
$includes(str, search)Check contains{{ $includes(message, "urgent") }}
$indexOf(str, search)Find position{{ $indexOf("hello", "l") }}2
$lastIndexOf(str, search)Find last position{{ $lastIndexOf("hello", "l") }}3
$match(str, pattern)Regex match{{ $match(text, "\\d+") }} → first number
$isEmpty(val)Check if empty{{ $isEmpty("") }}true
$isNotEmpty(val)Check if not empty{{ $isNotEmpty(name) }}true

String Transforms

FunctionDescriptionExample
$capitalize(str)Capitalize first letter{{ $capitalize("hello") }}"Hello"
$titleCase(str)Title Case Each Word{{ $titleCase("hello world") }}"Hello World"
$camelCase(str)camelCase conversion{{ $camelCase("hello world") }}"helloWorld"
$snakeCase(str)snake_case conversion{{ $snakeCase("helloWorld") }}"hello_world"
$kebabCase(str)kebab-case conversion{{ $kebabCase("helloWorld") }}"hello-world"
$padStart(str, len, char)Pad at start{{ $padStart("5", 3, "0") }}"005"
$padEnd(str, len, char)Pad at end{{ $padEnd("5", 3, "0") }}"500"
$repeat(str, count)Repeat string{{ $repeat("=", 10) }}"=========="
$reverse(val)Reverse string/array{{ $reverse("hello") }}"olleh"

Array Helpers

FunctionDescriptionExample
$first(arr)Get first element{{ $first(items) }}
$last(arr)Get last element{{ $last(items) }}
$nth(arr, n)Get nth element{{ $nth(items, 2) }}
$count(val)Count elements/length{{ $count(items) }}5
$unique(arr)Remove duplicates{{ $unique([1,1,2]) }}[1,2]
$flatten(arr, depth)Flatten nested arrays{{ $flatten([[1,2],[3,4]]) }}[1,2,3,4]
$sort(arr, key)Sort ascending{{ $sort(users, "name") }}
$sortDesc(arr, key)Sort descending{{ $sortDesc(scores) }}
$filter(arr, key, val)Filter by property{{ $filter(users, "active", true) }}
$map(arr, key)Extract property values{{ $map(users, "name") }}["Alice","Bob"]
$find(arr, key, val)Find first match{{ $find(users, "id", 123) }}
$pluck(arr, key)Same as $map{{ $pluck(items, "price") }}
$compact(arr)Remove falsy values{{ $compact([0,1,"",2]) }}[1,2]
$chunk(arr, size)Split into chunks{{ $chunk([1,2,3,4], 2) }}[[1,2],[3,4]]

Math Helpers

FunctionDescriptionExample
$min(arr)Minimum value{{ $min([3,1,4]) }}1
$max(arr)Maximum value{{ $max([3,1,4]) }}4
$sum(arr)Sum of values{{ $sum([1,2,3]) }}6
$avg(arr)Average value{{ $avg([1,2,3]) }}2
$abs(n)Absolute value{{ $abs(-5) }}5
$ceil(n)Round up{{ $ceil(4.2) }}5
$floor(n)Round down{{ $floor(4.8) }}4
$round(n, decimals)Round to decimals{{ $round(3.14159, 2) }}3.14
$randomInt(min, max)Random integer{{ $randomInt(1, 100) }}42
$clamp(n, min, max)Clamp to range{{ $clamp(150, 0, 100) }}100
$percent(val, total)Calculate percentage{{ $percent(25, 100) }}"25.00"

Type Conversion

FunctionDescriptionExample
$toNumber(val)Convert to number{{ $toNumber("42") }}42
$toString(val)Convert to string{{ $toString(42) }}"42"
$toBoolean(val)Convert to boolean{{ $toBoolean(1) }}true
$toJSON(val, indent)Convert to JSON{{ $toJSON(obj, 2) }}
$fromJSON(str)Parse JSON string{{ $fromJSON('{"a":1}') }}
$toArray(val)Wrap in array{{ $toArray("a") }}["a"]
$type(val)Get type name{{ $type([]) }}"array"

Encoding

FunctionDescriptionExample
$base64Encode(str)Encode to Base64{{ $base64Encode("hello") }}
$base64Decode(str)Decode from Base64{{ $base64Decode("aGVsbG8=") }}
$encodeURI(str)URL encode{{ $encodeURI("hello world") }}"hello%20world"
$decodeURI(str)URL decode{{ $decodeURI("hello%20world") }}
$encodeHTML(str)HTML entity encode{{ $encodeHTML("<div>") }}"&lt;div&gt;"

Conditional Helpers

FunctionDescriptionExample
$if(cond, true, false)Conditional value{{ $if(score > 50, "pass", "fail") }}
$default(val, fallback)Default if empty{{ $default(name, "Guest") }}
$coalesce(...args)First non-empty value{{ $coalesce(nickname, name, "User") }}
$switch(val, cases, default)Switch/case{{ $switch(status, {"active":"Yes"}, "No") }}

Date Helpers

FunctionDescriptionExample
$formatDate(date, format)Format dateSee formats below
$dateAdd(date, amount, unit)Add time{{ $dateAdd($today, 7, "days") }}
$dateDiff(d1, d2, unit)Difference{{ $dateDiff(startDate, endDate, "days") }}
$year(date)Get year{{ $year($today) }}2024
$month(date)Get month (1-12){{ $month($today) }}12
$day(date)Get day of month{{ $day($today) }}25
$dayOfWeek(date)Get day of week (0-6){{ $dayOfWeek($today) }}3
$hour(date)Get hour (0-23){{ $hour($timestamp) }}10
$minute(date)Get minute{{ $minute($timestamp) }}30

Date Formats for $formatDate:

FormatOutput Example
"iso""2024-12-25T10:30:00.000Z"
"date""2024-12-25"
"time""10:30:00"
"datetime""2024-12-25 10:30:00"
"relative""2h ago", "5d ago"

Advanced Helpers

FunctionDescriptionExample
$jmespath(query, data)JMESPath query{{ $jmespath("users[?active].name", data) }}
$keys(obj)Object keys{{ $keys({a:1,b:2}) }}["a","b"]
$values(obj)Object values{{ $values({a:1,b:2}) }}[1,2]
$entries(obj)Object entries{{ $entries({a:1}) }}[["a",1]]
$get(obj, path, default)Deep get{{ $get(user, "profile.email", "N/A") }}
$merge(...objs)Merge objects{{ $merge(defaults, overrides) }}
$pick(obj, ...keys)Pick properties{{ $pick(user, "name", "email") }}
$omit(obj, ...keys)Omit properties{{ $omit(user, "password") }}

Variable Validation

Valid Variable Names

  • Must start with letter, _, or $
  • Can contain letters, numbers, _, $
  • No hyphens (interpreted as subtraction)
  • No spaces
ValidInvalidWhy
userNameuser-nameHyphen = subtraction
user_nameuser nameSpaces not allowed
$count123countMust start with letter/$/_
_private@special@ not allowed

Error Messages

The editor shows helpful errors for common mistakes:

Undefined variable:

Template error: Variable 'userName' is not defined. Fix: Add 'userName' to the prompt metadata variables

Invalid syntax (hyphenated name):

Template syntax error: Variable name contains hyphens. Problem: {{ user-name }} Fix: Rename to {{ user_name }} or {{ userName }}

Metadata Inheritance

Variables can be inherited from parent folders:

How It Works

  1. Folders can define variables in their metadata
  2. Prompts in that folder inherit those variables
  3. Prompts can override inherited values
  4. Nested folders inherit from their parents

Example Hierarchy

marketing/ # Defines: brand_name, tone ├── email-templates/ # Inherits brand_name, tone; Adds: signature │ ├── welcome.md # Uses: brand_name, tone, signature │ └── newsletter.md # Uses: brand_name, tone, signature └── social/ # Inherits brand_name, tone; Adds: platform └── twitter-post.md # Uses: brand_name, tone, platform

Viewing Inherited Variables

In the Metadata panel, inherited variables appear with a folder icon and show their source:

Variables ├── brand_name (from: marketing) ← inherited ├── tone (from: marketing) ← inherited └── greeting ← defined here

Escaping Variables

Sometimes you need literal {{ }} in your output (e.g., for Jinja templates, code examples, or documentation):

Escape Individual Variables

Use backslash \ before the braces to escape:

\{{example}} renders as → {{example}}

Examples:

InputOutput
\{{name}}{{name}}
Hello {{ name }}, use \{{variable}} syntaxHello Alice, use {{variable}} syntax
Template: \{{user.email}}Template: {{user.email}}

This is useful for:

  • Including code snippets with template syntax
  • Writing documentation about variables
  • Passing variable syntax to LLMs

Disable for Entire Prompt

For prompts that should never have variables rendered:

  1. Open Metadata panel
  2. Toggle Disable Variables ON
  3. All {{ }} will be preserved literally

Use this when the entire prompt content should remain as-is.

Practical Examples

Dynamic Greeting

{{ $if($hour($now) < 12, "Good morning", $if($hour($now) < 17, "Good afternoon", "Good evening")) }}, {{ $capitalize(name) }}!

Formatted Price

Total: ${{ $round(price * quantity * 1.08, 2) }} (includes 8% tax)

List Formatting

Your items: {{ $join($map(items, "name"), "\n- ") }} Total items: {{ $count(items) }}

Conditional Content

{{ $if(isPremium, "Welcome back, Premium member! Here are your exclusive offers:", "Upgrade to Premium for exclusive benefits!") }}

Date Calculations

Your subscription renews on {{ $formatDate($dateAdd($today, 30, "days"), "date") }}. That's {{ $dateDiff($today, renewalDate, "days") }} days from now.
Last updated on