Filters in Jinja templates
Learn how to use filters in Jinja.
Introduction
Jinja templates are a powerful way to create dynamic prompts. You can use Jinja templates to create prompts that are tailored to the user’s input.
In this guide, we will show you how to use filters in Jinja. You can also learn how to use filters in the prompt editor.
Filters
In Jinja, filters are functions that modify variables in templates. They work similarly to functions in Python but are used within Jinja templates to transform output dynamically. Filters are applied using a pipe |
symbol.
Basic Syntax
You can also chain multiple filters:
Common Jinja Filters
Here are some frequently used filters:
1. String Filters
lower
: Converts a string to lowercase.
upper
: Converts a string to uppercase.
title
: Capitalizes the first letter of each word.
capitalize
: Capitalizes the first letter of the string.
reverse
: Reverses the string.
2. List & Collection Filters
length
: Returns the number of items in a list or string.
join
: Joins a list of strings into a single string.
first
: Returns the first item in a list.
sort
: Returns the last item in a list.
3. Number Filters
round
: Rounds a number to a specified number of decimal places.
abs
: Returns the absolute value of a number.
Custom Filters
You can also create your own filters. You can define custom filters in Python and use them in Jinja:
Then you can use it in Jinja:
Was this page helpful?