Jinja in Prompt Builder Guide

This guide covers all supported features for writing prompt templates in Prompt Builder.

Prompt templates in Prompt Builder are built on Jinja. At runtime, Prompt Builder populates the template from grounded data and evaluates expressions to include or exclude text in the completed prompt sent to the large language model. Prompt Builder uses the Block Editor. This topic describes Jinja syntax, the Jinja features Prompt Builder supports, and how Prompt Builder evaluates the language.

See Prompt Builder help pages for more information:

Basic Syntax 

Variable Substitution 

Use double curly braces to insert values:

Variable Substitution
1Hello {{ name }}!
2Welcome to {{ company }}.

Accessing Nested Data 

Use dot notation to access nested properties:

Access Nested Data
1{{ User.Name }}
2{{ Account.Address.City }}
3{{ Order.Items[0].Name }}

Comments 

Comments are not rendered in the output:

Comments
1{# This is a comment #}
2{{ name }} {# inline comment #}

Operators 

Arithmetic Operators 

OperatorDescriptionExample
+Addition{{ a + b }}
-Subtraction{{ a - b }}
*Multiplication{{ a * b }}
/Division{{ a / b }}
//Floor division{{ a // b }}
%Modulo{{ a % b }}
**Power{{ a ** 2 }}

Logical Operators 

OperatorDescriptionExample
andLogical AND{% if a and b %}
orLogical OR{% if a or b %}
notLogical NOT{% if not a %}

Comparison Operators 

OperatorDescriptionExample
==Equal{% if a == b %}
!=Not equal{% if a != b %}
>Greater than{% if a > b %}
<Less than{% if a < b %}
>=Greater or equal{% if a >= b %}
<=Less or equal{% if a <= b %}
inMembership test{% if item in items %}
not inNegated membership{% if item not in items %}

Unary Operators 

OperatorDescriptionExample
-Negative{{ -value }}
+Positive{{ +value }}

Control Structures 

Conditionals 

Conditional
1{% if condition %}
2    Content when true
3{% elif other_condition %}
4    Alternative content
5{% else %}
6    Default content
7{% endif %}

Example:

Conditional Example
1{% if User.Role == "admin" %}
2    You have full access.
3{% elif User.Role == "editor" %}
4    You can edit content.
5{% else %}
6    You have read-only access.
7{% endif %}

Loops 

Loop
1{% for item in items %}
2    {{ item }}
3{% endfor %}

With index:

Loop with Index
1{% for item in items %}
2    {{ loop.index }}. {{ item.name }}
3{% endfor %}

Loop variables:

VariableDescription
loop.indexCurrent iteration (1-indexed)
loop.index0Current iteration (0-indexed)
loop.firstTrue if first iteration
loop.lastTrue if last iteration
loop.lengthTotal number of items

Empty loop handling:

Empty Loop
1{% for item in items %}
2    {{ item }}
3{% else %}
4    No items found.
5{% endfor %}

Range loops:

Range Loop
1{% for i in range(5) %}
2    Item {{ i }}
3{% endfor %}

Note: Range is limited to 1000 items maximum.

Loop controls:

You can use break and continue to control loop execution:

Loop Controls
1{% for item in items %}
2    {% if item.skip %}
3        {% continue %}
4    {% endif %}
5    {% if item.stop %}
6        {% break %}
7    {% endif %}
8    {{ item.name }}
9{% endfor %}

Available Functions 

Type Conversion 

FunctionDescriptionExample
str(value)Convert to string{{ str(123) }}
int(value)Convert to integer{{ int("42") }}
float(value)Convert to float{{ float("3.14") }}
bool(value)Convert to boolean{{ bool(1) }}

Collection Functions 

FunctionDescriptionExample
list(value)Convert to list{{ list(items) }}
dict()Create dictionary{{ dict(a=1, b=2) }}
tuple(value)Convert to tuple{{ tuple(items) }}
set(value)Convert to set{{ set(items) }}
sorted(items)Sort items{{ sorted(names) }}
reversed(items)Reverse items{{ reversed(items) }}
zip(a, b)Zip iterables{% for x, y in zip(a, b) %}

Utility Functions 

FunctionDescriptionExample
len(value)Get length{{ len(items) }}
max(items)Maximum value{{ max(scores) }}
min(items)Minimum value{{ min(scores) }}
sum(items)Sum of items{{ sum(prices) }}
abs(value)Absolute value{{ abs(-5) }}
round(value)Round number{{ round(3.7) }}
range(n)Generate range{% for i in range(10) %}

Filters 

Filters modify values using the pipe (|) syntax:

Filter Syntax
1{{ value|filter }}
2{{ value|filter(arg) }}

Available Filters 

FilterDescriptionExample
default(value)Provide default if undefined/none`{{ name
trimRemove leading/trailing whitespace`{{ text
upperConvert to uppercase`{{ name
lowerConvert to lowercase`{{ name
lengthGet length of string/list`{{ items
firstGet first item`{{ items
lastGet last item`{{ items
join(separator)Join list into string`{{ items
selectattr(attr[, test, value])Filter a list of objects by an attribute`{{ users

Examples:

Filter Examples
1{{ User.Name|default("Anonymous") }}
2{{ description|trim|upper }}
3{{ tags|join(", ") }}
4{{ items|first }}

selectattr — pick items from a list by attribute value:

Without a test, selectattr keeps items whose attribute is truthy:

selectattr Without a Test
1{% for u in users|selectattr("active") %}{{ u.name }}{% endfor %}

With a test (e.g. eq), selectattr keeps items where the attribute matches the given value. Combine with |first to pull a single item by id:

selectattr with a Test
1{{ (products|selectattr("id", "eq", target_id)|first).name }}

Context:

selectattr Context
1{
2  "products": [
3    { "id": 1, "name": "laptop" },
4    { "id": 2, "name": "mouse" },
5    { "id": 3, "name": "keyboard" }
6  ],
7  "target_id": 2
8}

Output:

selectattr Output
1mouse

Tests 

Tests check conditions using the is keyword:

Tests
1{% if value is test %}
2{% if value is not test %}

Available Tests 

TestDescriptionExample
noneValue is None{% if value is none %}
definedVariable exists{% if name is defined %}
undefinedVariable doesn’t exist{% if name is undefined %}
trueValue is true{% if flag is true %}
falseValue is false{% if flag is false %}
stringValue is a string{% if value is string %}
numberValue is a number{% if value is number %}
integerValue is an integer{% if value is integer %}
floatValue is a float{% if value is float %}
sequenceValue is a sequence{% if items is sequence %}
mappingValue is a dict{% if data is mapping %}
iterableValue is iterable{% if items is iterable %}
evenNumber is even{% if num is even %}
oddNumber is odd{% if num is odd %}
eq(value)Value equals the given value (also usable as a selectattr test){% if status is eq("active") %}
ne(value)Value is not equal to the given value{% if status is ne("inactive") %}
gt(value)Value is greater than the given value{% if price is gt(100) %}
ge(value)Value is greater than or equal to the given value{% if price is ge(100) %}
lt(value)Value is less than the given value{% if price is lt(100) %}
le(value)Value is less than or equal to the given value{% if price is le(100) %}

Handling None Values 

When a value is None, it renders as a placeholder:

None Value
1{{ User.Name }}

If User.Name is None, output:

None Placeholder Output
1[Provide:{NAME}]

Checking for None 

Check for None
1{% if value is none %}
2    Value is not provided
3{% else %}
4    Value: {{ value }}
5{% endif %}

Conditional Display 

Conditional Display
1{% if User.Email is not none %}
2    Contact: {{ User.Email }}
3{% endif %}

Whitespace Control 

By default, the newline after block tags ({% if %}, {% for %}, {% endif %}, etc.) is automatically removed. This keeps your output clean without extra blank lines.

For additional whitespace control, use - inside tags:

Whitespace Control
1{%- if condition -%}    {# strips whitespace on both sides #}
2    content
3{%- endif -%}
SyntaxEffect
{%-Strip whitespace before
-%}Strip whitespace after
{{-Strip whitespace before
-}}Strip whitespace after

Ternary Expressions 

Ternary Expressions
1{{ "Yes" if condition else "No" }}
2{{ value if value else "default" }}

Variable Assignment 

Set Statement 

Use {% set %} to create or modify variables:

Set Statement
1{% set greeting = "Hello" %}
2{% set full_name = User.FirstName ~ " " ~ User.LastName %}
3{{ greeting }}, {{ full_name }}!

Block assignment for multi-line content:

Block Assignment
1{% set message %}
2    Welcome to {{ company }}.
3    Your account is {{ status }}.
4{% endset %}
5{{ message }}

With Statement 

Create scoped variables that only exist within the block:

With Statement
1{% with total = items|length %}
2    There are {{ total }} items.
3{% endwith %}

Multiple variables:

With Multiple Variables
1{% with first = items|first, last = items|last %}
2    First: {{ first }}, Last: {{ last }}
3{% endwith %}

Inline Data Structures 

Lists 

Create lists directly in templates:

Inline List
1{% set colors = ["red", "green", "blue"] %}
2{% for color in colors %}
3    {{ color }}
4{% endfor %}

Dictionaries 

Create dictionaries inline:

Inline Dictionary
1{% set person = {"name": "Alice", "age": 30} %}
2{{ person.name }} is {{ person.age }} years old.

Tuples 

Create tuples for immutable sequences:

Inline Tuple
1{% set point = (10, 20) %}
2X: {{ point[0] }}, Y: {{ point[1] }}

String Concatenation 

Use the ~ operator to concatenate strings:

String Concatenation
1{{ "Hello, " ~ name ~ "!" }}
2{% set full_name = first ~ " " ~ last %}

Slicing 

Access portions of sequences using slice notation:

Slicing
1{{ items[0] }}          {# First item #}
2{{ items[-1] }}         {# Last item #}
3{{ items[1:3] }}        {# Items 1 and 2 #}
4{{ items[:3] }}         {# First 3 items #}
5{{ items[2:] }}         {# From item 2 to end #}
6{{ name[0:5] }}         {# First 5 characters #}

Expression Statements 

Use {% do %} to execute expressions without output (useful for method calls):

Expression Statement
1{% do items.append(new_item) %}
2{% do log.debug("Processing complete") %}

Examples 

Basic Variable Substitution 

Template:

Variable Substitution Template
1Hello {{ User.Name }}!
2Your role is {{ User.Role }}.

Context:

Variable Substitution Context
1{ "User": { "Name": "Alice", "Role": "admin" } }

Output:

Variable Substitution Output
1Hello Alice!
2Your role is admin.

Conditionals 

Template:

Conditional Template
1Hello {{ User.Name }}!
2{% if User.Role == "admin" %}
3You have administrator privileges.
4{% endif %}
5Welcome to the system.

Context:

Conditional Context
1{ "User": { "Name": "Alice", "Role": "admin" } }

Output:

Conditional Output
1Hello Alice!
2You have administrator privileges.
3Welcome to the system.

Loop Example 

Template:

Loop Template
1Your order contains {{ len(items) }} items:
2{% for item in items %}
3- {{ item.Name }}: ${{ item.Price }}
4{% endfor %}

Context:

Loop Context
1{
2  "items": [
3    { "Name": "Widget", "Price": 10 },
4    { "Name": "Gadget", "Price": 25 }
5  ]
6}

Output:

Loop Output
1Your order contains 2 items:
2- Widget: $10
3- Gadget: $25

Handling None Values 

Template:

None Value Template
1Name: {{ User.Name }}
2Email: {{ User.Email }}

Context:

None Value Context
1{ "User": { "Name": "Alice", "Email": null } }

Output:

None Value Output
1Name: Alice
2Email: [Provide:{EMAIL}]

Conditional None Check 

Template:

Conditional None Check Template
1{% if Account.Industry is not none %}
2Industry: {{ Account.Industry }}
3{% endif %}
4{% if Account.Website is not none %}
5Website: {{ Account.Website }}
6{% endif %}

Context:

Conditional None Check Context
1{ "Account": { "Industry": "Technology", "Website": null } }

Output:

Conditional None Check Output
1Industry: Technology