Smart Chain Engine

Smart Chain Engine

Introduction

The smart chain engine is the central component that allows for customization of every aspect of Prospera Labs system. Generally speaking, you should not need to interact with the smart chain engine unless you are trying to customize the behavior of a premade agent or build a custom agent from scratch.

Features

  1. Provides an access point to customize behaviors and features deep within the Prospera Labs engine

  2. Provides ability for partners to customize agents on behalf of the customers that then log into their system

  3. A complete template engine to provide programmatic ways of setting options and building prompts

  4. Ability to tie multiple prompts together into prompt-chains, similar to tools like LangGraph or our own older FlowThought / prompt chart tool

  5. Able to use many different forms of AI prompting, from system prompts, conversational prompts, tool selections, structured JSON outputs, ranked selections with confidence scores, and more

  6. Provides direct access to LLM model inputs and outputs without processing by the surrounding system, allowing us to use pretty much any prompting technique that works with the underlying models

  7. Able to perform actions like writing data to the agents database, and incorporating data pulled from the database into prompts

  8. Able to quickly switch which particular smart-chain is used for what within the system through the binding system

How it Works

When the system is distilled down to its most basic essence, the smart chain system is just a simple text processing engine with emphasis on LLM based processing steps. A smart chain takes JSON data on the input, and produces JSON data as its output. The individual steps within a smart chain work the same way - taking JSON as their input and producing JSON as their output.

Smart Chain Engine - High Level Overview.png

Each time that a smart chain is invoked, it will go through the following process in order to compute the result:

Smart Chain Engine.png

Those steps are as follows:

  1. Some section of code submits for a smart chain to get executed, providing a specific binding_name and a PromptContext object. The prompt context object itself needs to be prefilled with several values, including a tenant_id, user_id and conversation_id (if needed).

  2. The system will invoke the get_data function on each of the smart chain data providers, accumulating a value for each one within the input data for the smart chain

  3. The system resolves the binding_name down to a specific smart chain. The process here is a bit more complex then whats described above, because there are also published versions of smart chains and built-in chains that are provided from code. But at the essence, we are trying to find the latest version available of the smart chain with a chain_name equal to what is set on the binding whose binding_name matches what was provided.

  4. Execution of the smart chain begins. Smart chains have multiple steps that are identical except that values can be fed from early steps into the input on later steps. Each step execution goes through the following processes:

    1. Compile the content template

    2. Run the content template, producing the content text

    3. Compile the options template

    4. Run the options template and then parse it as JSON, producing the options JSON object

    5. Execute the smart chain step by providing the accumulated data from the data providers and prior step outputs, the content, and the options. Each different type of smart chain step has different code associated with it.

    6. The result data from the smart chain step is then merged with the current input data, and the next step in the smart chain is executed

  5. The output of the last step in the sequence becomes the output for the smart chain as a whole. The smart chain engine returns this output JSON object and execution completes.

Agents and Bots

Since the smart chain system is really just a general purpose text processing and prompt chaining engine, you might reasonably ask, how exactly can you build a bot or an agent with this system?

The smart chain system constructs agents by executing several special step types which allow one to choose tools for an agent to perform and maintain a conversation history. The most basic construction for an Agent within the Prospera system has the following form:

  1. A Conversational Tool Selection step, often called select_action, which runs an LLM prompt and has the LLM decide which action for the agent to perform

  2. A Conversational Agent Action step, often called execute_action, which calls the appropriate agent module with the parameters selected by the LLM

  3. A Record Agent Action step, often called record_action, which records the action executed in the second step into the bots conversation history.

Agents we construct can get more complex then this, but this is the most basic construction. When you record an event to the conversation history, that becomes the events that you see on this screen:

image-20250121-130433.png

Another key distinction with smart-chains that are intended to be used with Agents and Bots versus other types of smart chains is the fact that the user can trigger them. Our system has various communication channels through which the bot can communicate. One which you can access directly is the Web Chat:

image-20250121-154721.png

When the user sends a message through this web interface, a new event gets added into the Conversation History. This happens completely outside of the smart chain system and is a function of how that particular communication channel is implemented.

image-20250121-154820.png

The communication channel will then trigger the Agent Kernel. The agent kernel will then attempt to figure out which smart chain should get activated for the bot. It will first check the Conversation object to see if there is any specific smart chain binding set. This can be seen under then Agent Name section of the conversation interface:

image-20250121-155013.png

If there is a specific smart chain binding set for this conversation, then that smart chain binding is invoked. If the Conversation is marked as default, then we will look up the default smart chain binding for that tenancy. That is set here within the Tenant configuration by the Prospera Labs team.

image-20250121-155236.png

Depending on which environment / tenant you are on, a different smart chain binding may be set as the default binding.

Main Loop

Once the agent kernel has executed the smart chain, the system is allowed to run a second time if there is a value for should_execute_another_action returned by the smart chain and it is set to True. There is a hard coded limit of a maximum of three smart chain invocations in when the kernel is triggered. This is to prevent the agent from going out of control and repeating forever if there is an error.

By default, any time the agent communicates with the user, such as by sending a message, email, or speaking, should_execute_another_action is set to False. When the agent performs some sort of action, such as doing a knowledge base lookup or checking the users schedule for a booking, should_execute_another_action is set to True.

This gives the agent an opportunity to follow up on the result from the action it took by telling the user what it did and what happened.

User Interface

Access to the smart chain system is found underneath the “Advanced” sub-menu within the “Configuration” menu:

image-20250118-181539.png

There are two different menus to access the smart chain system. One is the Smart Chains themselves, and the other are Smart Chain Bindings.

In both cases, when you click the menu link, you will be brought to a table view that allows you to search through the data.

If you are looking at a brand new account, all you will see are the built-in smart chains. These built-in chains can be distinguished because they have no data in the “user_id” column. By contrast, any smart chains that you have created yourself or you have modified will show some value in the “user_id” column.

image-20250118-182916.png

The built-in smart chains are being continuously updated and improved by our team. However, you are still free to modify them. If you do modify them, then you will no longer receive any of the changes that our team puts in. Often modifying a smart chain is the only way to get a specific or custom behavior you are looking for.

Editor

If you click into a specific smart chain, you will be brought to the smart chain editor, which as of right now looks like this:

image-20250118-183302.png

Sometimes it can be convenient to shrink the left side menu so that you have more space for the editor:

image-20250118-183415.png
image-20250118-183429.png

Tool-bar

image-20250118-184151.png
image-20250118-184437.png
image-20250118-184656.png

Step Types

Prompt Chaining

In many situations, it is necessary to chain together multiple different AI prompts, feeding the output of one as the input of another. This is trivial to accomplish within the Smart Chain system.

To understand how this works, we must first observe that each smart chain step has a name. The names can be observed when you open the list of smart chain steps:

image-20250121-010734.png

When a smart chain step produces an output, that output is duplicated in two places within the final output object. First it is saved directly into the output object, and second, it is saved in a sub-object with the given step name. This can be observed when you examine the output data schema for a smart chain step.

image-20250121-011105.png

You will notice that the second sub object has a key that is the same as the name of the step. This gives you two options to reference data from prior steps. You can reference either the variable directly, or you can reference it through the individual step name. Those two variations are seen below in the record_action step.

You can reference a variable directly, as seen here:

image-20250121-011316.png

Or you can use ‘dot’ notation in order to reference the sub variable within a particular step, as seen here:

image-20250121-011410.png

Which option you choose depends entirely on you. But its important to remember that if multiple different steps have outputs with the same field name, the later step values will overwrite the earlier step values. This usually isn’t a problem, but can be important to understand when using common variable names like text

Test Samples & Replay

Within the smart chain editor, you will find a tab called Test Samples. This allows you to view recent executions of the smart chain step. If we take for granted that the smart chain system is, at its essence, a system that takes a JSON as input and produces JSON as output:

Smart Chain Engine - High Level Overview.png

Those JSON objects manifest very literally within the user-interface under the Test Samples tab:

image-20250121-004237.png

In fact, the JSON’ish nature of the data can be even more clearly seen by pressing the button in the top-right corner of the widget:

image-20250121-004549.png
image-20250121-004628.png

By default, the Test Samples view shows you the most recent executions of this smart chain step. You can also elect to get a random selection of executions. That option is more useful when doing one-off prompts and prompt-chains that don’t involve conversations.

Replay

The most useful part of the Test Samples interface is the ‘replay’ functionality. That is the button you see in the center here:

image-20250121-004855.png

When you press this button, the Smart Chain Step will re-execute using the latest options and latest prompt, but the same input-data as what you see on the interface. This can be very useful if you are trying to change the behaviour of the agent. You can update the prompt and then see if your new prompt has changed the behaviour in the way you expect, knowing that it was run with all of the exact same data, and the only thing that changed was your prompt.

When you rerun a smart chain step, any side effects that run as a consequence of that action will occur a second time. For example, if the smart chain step involves sending a message to the user, rerunning that step will result in additional messages being sent to the user. Generally it is only reccomended to rerun smart chain steps that use an LLM or perform a computation. There are few reasons to rerun the Conversational Agent Action or Record Agent Action steps.

Recursion - Calling One Smart Chain From Within Another

Smart chains can execute other smart chains as part of evaluating either the Content Template or the Options Template.

All smart chain bindings are loaded into the smart chain system as functions. So if you have a binding that is named “formatted_business_info”, as seen here:

image-20250121-005746.png

You can then invoke that smart chain by calling it as a function within your template. This can be seen in action within the built-in Receptionist smart chains.

image-20250121-005906.png

When you invoke a different smart chain, it will receive the same prompt context as the smart chain that did the invocation. Additionally, any side-effects that result from that other smart chain will also occur when that smart chain is invoked. This allows you to, if you put in some effort, to do primitive functions and conditional executions of smart chain sections.

Bindings and Published Versions

Smart chain bindings are used to reference smart chains. There is no way to access a smart chain EXCEPT through its binding. Any time that there are sections of our code that need to reference or execute a smart chain, it is done through a binding. Any time that smart chains reference each other, it is done through bindings.

Why have the bindings? The bindings provide us a mechanism to easily flip between different versions of a particular smart chain. For example, you may want to prepare a new version of a smart chain that is a significant change from your current version. Through the binding, you can keep the system pointed towards the current smart chain, but then flip it over to the new smart chain whenever it is ready.

In the future, we may add additional features to the binding system, such as an ability to directly A/B test different versions of a smart chain and measure the difference in metrics that result. Or we may be able to provide fallback smart-chains that are automatically invoked if there is a failure in a main version.

Additionally, smart chains themselves have a system that allow you to publish versions. That can be accessed through this button:

image-20250121-014747.png

When you publish a smart chain for the first time, that published version will then take precedence over whatever is currently being edited. You will see your newly published version show up on this menu:

image-20250121-014908.png

This also allows you to revert whatever version is currently in your editor to a previous published and verified version.

image-20250121-015046.png

The binding system is defined by two variables: the binding_name and the chain_name. The binding_name is what you see in this column in the binding view:

image-20250121-015152.png

The binding system really breaks down to just a way to define key value pairs, where the key is the binding_name and the value is the chain_name.

image-20250121-015258.png

The chain_name refers to the name of the smart chain, which can be edited HERE within the UI:

image-20250121-015347.png

The chain_name and binding_name are used to disambiguate smart chains and bindings within the database. Some smart chains and some bindings are built-in. If you do not have a smart chain or a binding with that chain_name or binding_name, then the default smart chain or default binding will be automatically inferred by the system.

Resolving the Binding

When the system attempts to resolve a given binding_name into a final smart chain, the following process is executed:

  1. Attempt to find any smart-chain binding object with the given binding_name and user_id from the users account

  2. If none found, attempt find a built in smart chain binding object with the given binding_name and user_id of null

  3. If no binding object is found, return an error

  4. Take the chain_name from the smart chain binding object

  5. Attempt to the latest published smart chain version with the chain_name taken from the binding and the user_id from the users account

  6. If no published version is found, we attempt to find any smart chain with the chain_name taken from the binding and the user_id from the users account

  7. If no user specific smart chain was found at all, we will attempt to find a built-in smart chain with the chain_name specified in the binding and user_id of null

  8. If no smart chain was found at all, return an error

 

Or to understand this in a simpler way, smart chains are resolved from bindings in the following priority:

  1. Published Smart Chains with matching chain_name local to the user

  2. Any smart chain at all with matching chain_name local to the user

  3. Default built-in smart chains with matching chain_name and user_id of null

Template Engine

The template engine allows users to write complex templates that may involve conditions, loops, variable references, and even simple calculations and function calls.

Variables

Variable substitutions use the double curly brace syntax:

{{variable_name}}

If you want to reference a variable within a variable, you can use either dot notation or square bracket notation:

{{sub_object.variable_name}} {{sub_object['variable_name']}}

The variables you reference here must be part of the prompts input. You can see what input variables are available by going here:

image-20250121-142858.png

Filters

Variables can be modified by filters. Filters are separated from the variable by a pipe symbol (|) and may have optional arguments in parentheses. Multiple filters can be chained. The output of one filter is applied to the next.

For example, {{ name|striptags|title }} will remove all HTML Tags from variable name and title-case the output (title(striptags(name))).

Filters that accept arguments have parentheses around the arguments, just like a function call. For example: {{ listx|join(', ') }} will join a list with commas (str.join(', ', listx)).

The List of Builtin Filters below describes all the builtin filters.

Tests

Beside filters, there are also so-called “tests” available. Tests can be used to test a variable against a common expression. To test a variable or expression, you add is plus the name of the test after the variable. For example, to find out if a variable is defined, you can do name is defined, which will then return true or false depending on whether name is defined in the current template context.

Tests can accept arguments, too. If the test only takes one argument, you can leave out the parentheses. For example, the following two expressions do the same thing:

{% if loop.index is divisibleby 3 %} {% if loop.index is divisibleby(3) %}

The List of Builtin Tests below describes all the builtin tests.

Comments

To comment-out part of a line in a template, use the comment syntax which is by default set to {# ... #}. This is useful to comment out parts of the template for debugging or to add information for other template designers or yourself:

{# note: commented-out template because we no longer use this {% for user in users %} ... {% endfor %} #}

Whitespace Control

In the default configuration:

  • a single trailing newline is stripped if present

  • other whitespace (spaces, tabs, newlines etc.) is returned unchanged

If an application configures the template engine to trim_blocks, the first newline after a template tag is removed automatically (like in PHP). The lstrip_blocks option can also be set to strip tabs and spaces from the beginning of a line to the start of a block. (Nothing will be stripped if there are other characters before the start of the block.)

With both trim_blocks and lstrip_blocks disabled (the default), block tags on their own lines will be removed, but a blank line will remain and the spaces in the content will be preserved. For example, this template:

<div> {% if True %} yay {% endif %} </div>

With both trim_blocks and lstrip_blocks disabled, the template is rendered with blank lines inside the div:

<div> yay </div>

With both trim_blocks and lstrip_blocks enabled, the template block lines are completely removed:

<div> yay </div>

You can manually disable the lstrip_blocks behavior by putting a plus sign (+) at the start of a block:

<div> {%+ if something %}yay{% endif %} </div>

Similarly, you can manually disable the trim_blocks behavior by putting a plus sign (+) at the end of a block:

<div> {% if something +%} yay {% endif %} </div>

You can also strip whitespace in templates by hand. If you add a minus sign (-) to the start or end of a block (e.g. a For tag), a comment, or a variable expression, the whitespaces before or after that block will be removed:

{% for item in seq -%} {{ item }} {%- endfor %}

This will yield all elements without whitespace between them. If seq was a list of numbers from 1 to 9, the output would be 123456789.

If Line Statements are enabled, they strip leading whitespace automatically up to the beginning of the line.

By default, the template engine also removes trailing newlines. To keep single trailing newlines, configure the template engine to keep_trailing_newline.

Note

You must not add whitespace between the tag and the minus sign.

valid:

{%- if foo -%}...{% endif %}

invalid:

{% - if foo - %}...{% endif %}

Escaping

It is sometimes desirable – even necessary – to have the template engine ignore parts it would otherwise handle as variables or blocks. For example, if, with the default syntax, you want to use {{ as a raw string in a template and not start a variable, you have to use a trick.

The easiest way to output a literal variable delimiter ({{) is by using a variable expression:

{{ '{{' }}

For bigger sections, it makes sense to mark a block raw. For example, to include example the template engine syntax in a template, you can use this snippet:

{% raw %} <ul> {% for item in seq %} <li>{{ item }}</li> {% endfor %} </ul> {% endraw %}

Note

Minus sign at the end of {% raw -%} tag cleans all the spaces and newlines preceding the first character of your raw data.

Line Statements

If line statements are enabled by the application, it’s possible to mark a line as a statement. For example, if the line statement prefix is configured to #, the following two examples are equivalent:

<ul> # for item in seq <li>{{ item }}</li> # endfor </ul> <ul> {% for item in seq %} <li>{{ item }}</li> {% endfor %} </ul>

The line statement prefix can appear anywhere on the line as long as no text precedes it. For better readability, statements that start a block (such as for, if, elif etc.) may end with a colon:

# for item in seq: ... # endfor

Note

Line statements can span multiple lines if there are open parentheses, braces or brackets:

<ul> # for href, caption in [('index.html', 'Index'), ('about.html', 'About')]: <li><a href="{{ href }}">{{ caption }}</a></li> # endfor </ul>

Line-based comments are available as well. For example, if the line-comment prefix is configured to be ##, everything from ## to the end of the line is ignored (excluding the newline sign):

# for item in seq: <li>{{ item }}</li> ## this comment is ignored # endfor

List of Control Structures

A control structure refers to all those things that control the flow of a program - conditionals (i.e. if/elif/else), for-loops, as well as things like macros and blocks. With the default syntax, control structures appear inside {% ... %} blocks.

For

Loop over each item in a sequence. For example, to display a list of users provided in a variable called users:

<h1>Members</h1> <ul> {% for user in users %} <li>{{ user.username|e }}</li> {% endfor %} </ul>

As variables in templates retain their object properties, it is possible to iterate over containers like dict:

<dl> {% for key, value in my_dict.items() %} <dt>{{ key|e }}</dt> <dd>{{ value|e }}</dd> {% endfor %} </dl>

Python dicts may not be in the order you want to display them in. If order matters, use the |dictsort filter.

<dl> {% for key, value in my_dict | dictsort %} <dt>{{ key|e }}</dt> <dd>{{ value|e }}</dd> {% endfor %} </dl>

Inside of a for-loop block, you can access some special variables:

Variable

Description

Variable

Description

loop.index

The current iteration of the loop. (1 indexed)

loop.index0

The current iteration of the loop. (0 indexed)

loop.revindex

The number of iterations from the end of the loop (1 indexed)

loop.revindex0

The number of iterations from the end of the loop (0 indexed)

loop.first

True if first iteration.

loop.last

True if last iteration.

loop.length

The number of items in the sequence.

loop.cycle

A helper function to cycle between a list of sequences. See the explanation below.

loop.depth

Indicates how deep in a recursive loop the rendering currently is. Starts at level 1

loop.depth0

Indicates how deep in a recursive loop the rendering currently is. Starts at level 0

loop.previtem

The item from the previous iteration of the loop. Undefined during the first iteration.

loop.nextitem

The item from the following iteration of the loop. Undefined during the last iteration.

loop.changed(*val)

True if previously called with a different value (or not called at all).

Within a for-loop, it’s possible to cycle among a list of strings/variables each time through the loop by using the special loop.cycle helper:

{% for row in rows %} <li class="{{ loop.cycle('odd', 'even') }}">{{ row }}</li> {% endfor %}

An extra cycle helper exists that allows loop-unbound cycling. For more information, have a look at the List of Global Functions.

Unlike in Python, it’s not possible to break or continue in a loop. You can, however, filter the sequence during iteration, which allows you to skip items. The following example skips all the users which are hidden:

{% for user in users if not user.hidden %} <li>{{ user.username|e }}</li> {% endfor %}

The advantage is that the special loop variable will count correctly; thus not counting the users not iterated over.

If no iteration took place because the sequence was empty or the filtering removed all the items from the sequence, you can render a default block by using else:

<ul> {% for user in users %} <li>{{ user.username|e }}</li> {% else %} <li><em>no users found</em></li> {% endfor %} </ul>

Note that, in Python, else blocks are executed whenever the corresponding loop did not break. Since the template engine loops cannot break anyway, a slightly different behavior of the else keyword was chosen.

It is also possible to use loops recursively. This is useful if you are dealing with recursive data such as sitemaps or RDFa. To use loops recursively, you basically have to add the recursive modifier to the loop definition and call the loop variable with the new iterable where you want to recurse.

The following example implements a sitemap with recursive loops:

<ul class="sitemap"> {%- for item in sitemap recursive %} <li><a href="{{ item.href|e }}">{{ item.title }}</a> {%- if item.children -%} <ul class="submenu">{{ loop(item.children) }}</ul> {%- endif %}</li> {%- endfor %} </ul>

The loop variable always refers to the closest (innermost) loop. If we have more than one level of loops, we can rebind the variable loop by writing {% set outer_loop = loop %} after the loop that we want to use recursively. Then, we can call it using {{ outer_loop(...) }}

Please note that assignments in loops will be cleared at the end of the iteration and cannot outlive the loop scope. Older versions of the template engine had a bug where in some circumstances it appeared that assignments would work. This is not supported. See Assignments for more information about how to deal with this.

If all you want to do is check whether some value has changed since the last iteration or will change in the next iteration, you can use previtem and nextitem:

{% for value in values %} {% if loop.previtem is defined and value > loop.previtem %} The value just increased! {% endif %} {{ value }} {% if loop.nextitem is defined and loop.nextitem > value %} The value will increase even more! {% endif %} {% endfor %}

If you only care whether the value changed at all, using changed is even easier:

{% for entry in entries %} {% if loop.changed(entry.category) %} <h2>{{ entry.category }}</h2> {% endif %} <p>{{ entry.message }}</p> {% endfor %}

If

The if statement in the template engine is comparable with the Python if statement. In the simplest form, you can use it to test if a variable is defined, not empty and not false:

{% if users %} <ul> {% for user in users %} <li>{{ user.username|e }}</li> {% endfor %} </ul> {% endif %}

For multiple branches, elif and else can be used like in Python. You can use more complex Expressions there, too:

{% if kenny.sick %} Kenny is sick. {% elif kenny.dead %} You killed Kenny! You bastard!!! {% else %} Kenny looks okay --- so far {% endif %}

If can also be used as an inline expression and for loop filtering.

Macros

Macros are comparable with functions in regular programming languages. They are useful to put often used idioms into reusable functions to not repeat yourself (“DRY”).

Here’s a small example of a macro that renders a form element:

{% macro input(name, value='', type='text', size=20) -%} <input type="{{ type }}" name="{{ name }}" value="{{ value|e }}" size="{{ size }}"> {%- endmacro %}

The macro can then be called like a function in the namespace:

<p>{{ input('username') }}</p> <p>{{ input('password', type='password') }}</p>

If the macro was defined in a different template, you have to import it first.

Inside macros, you have access to three special variables:

varargs

If more positional arguments are passed to the macro than accepted by the macro, they end up in the special varargs variable as a list of values.

kwargs

Like varargs but for keyword arguments. All unconsumed keyword arguments are stored in this special variable.

caller

If the macro was called from a call tag, the caller is stored in this variable as a callable macro.

Macros also expose some of their internal details. The following attributes are available on a macro object:

name

The name of the macro. {{ input.name }} will print input.

arguments

A tuple of the names of arguments the macro accepts.

catch_kwargs

This is true if the macro accepts extra keyword arguments (i.e.: accesses the special kwargs variable).

catch_varargs

This is true if the macro accepts extra positional arguments (i.e.: accesses the special varargs variable).

caller

This is true if the macro accesses the special caller variable and may be called from a call tag.

If a macro name starts with an underscore, it’s not exported and can’t be imported.

Due to how scopes work in the template engine, a macro in a child template does not override a macro in a parent template. The following will output “LAYOUT”, not “CHILD”.

layout.txt

{% macro foo() %}LAYOUT{% endmacro %} {% block body %}{% endblock %}

child.txt

{% extends 'layout.txt' %} {% macro foo() %}CHILD{% endmacro %} {% block body %}{{ foo() }}{% endblock %}

Call

In some cases it can be useful to pass a macro to another macro. For this purpose, you can use the special call block. The following example shows a macro that takes advantage of the call functionality and how it can be used:

{% macro render_dialog(title, class='dialog') -%} <div class="{{ class }}"> <h2>{{ title }}</h2> <div class="contents"> {{ caller() }} </div> </div> {%- endmacro %} {% call render_dialog('Hello World') %} This is a simple dialog rendered by using a macro and a call block. {% endcall %}

It’s also possible to pass arguments back to the call block. This makes it useful as a replacement for loops. Generally speaking, a call block works exactly like a macro without a name.

Here’s an example of how a call block can be used with arguments:

{% macro dump_users(users) -%} <ul> {%- for user in users %} <li><p>{{ user.username|e }}</p>{{ caller(user) }}</li> {%- endfor %} </ul> {%- endmacro %} {% call(user) dump_users(list_of_user) %} <dl> <dt>Realname</dt> <dd>{{ user.realname|e }}</dd> <dt>Description</dt> <dd>{{ user.description }}</dd> </dl> {% endcall %}

Filters

Filter sections allow you to apply regular the template engine filters on a block of template data. Just wrap the code in the special filter section:

{% filter upper %} This text becomes uppercase {% endfilter %}

Filters that accept arguments can be called like this:

{% filter center(100) %}Center this{% endfilter %}

Assignments

Inside code blocks, you can also assign values to variables. Assignments at top level (outside of blocks, macros or loops) are exported from the template like top level macros and can be imported by other templates.

Assignments use the set tag and can have multiple targets:

{% set navigation = [('index.html', 'Index'), ('about.html', 'About')] %} {% set key, value = call_something() %}

Scoping Behavior

Please keep in mind that it is not possible to set variables inside a block and have them show up outside of it. This also applies to loops. The only exception to that rule are if statements which do not introduce a scope. As a result the following template is not going to do what you might expect:

{% set iterated = false %} {% for item in seq %} {{ item }} {% set iterated = true %} {% endfor %} {% if not iterated %} did not iterate {% endif %}

It is not possible with the template engine syntax to do this. Instead use alternative constructs like the loop else block or the special loop variable:

{% for item in seq %} {{ item }} {% else %} did not iterate {% endfor %}

As of version 2.10 more complex use cases can be handled using namespace objects which allow propagating of changes across scopes:

{% set ns = namespace(found=false) %} {% for item in items %} {% if item.check_something() %} {% set ns.found = true %} {% endif %} * {{ item.title }} {% endfor %} Found item having something: {{ ns.found }}