Sling Academy
Home/FastAPI/Popular useful built-in Jinja filters you should know

Popular useful built-in Jinja filters you should know

Last updated: November 28, 2024

Jinja is a powerful templating engine for Python, commonly used to render web templates. One of its most practical features is the availability of built-in filters, which can manipulate template data effectively. Let's explore some of the most useful Jinja filters with examples on how to use them.

1. safe

The safe filter is used to mark strings as safe, prohibiting auto-escaping for HTML output. This is crucial when you want to render HTML elements within variables.

from jinja2 import Template

template = Template("""
   {{ user_description | safe }}
""")

output = template.render(user_description="<p>Hello, World!</p>")
print(output)  # Output: <div><p>Hello, World!</p></div>

2. upper

The upper filter converts strings to uppercase, which is particularly useful for consistency in text formatting.

template = Template("{{ name | upper }}")

output = template.render(name="John Doe")
print(output)  # Output: JOHN DOE

3. capitalize

Using the capitalize filter capitalizes a string (i.e., it makes the first character uppercase and the rest lowercased).

template = Template("{{ sentence | capitalize }}")

output = template.render(sentence="hello world!")
print(output)  # Output: Hello world!

4. default

The default filter allows setting a default value if the passed variable is undefined, which enhances template robustness significantly.

template = Template("{{ user_name | default('Guest') }}")

output = template.render()  # user_name is not provided
print(output)  # Output: Guest

5. join

With the join filter, you can concatenate list elements into a single string, using a specified separator.

template = Template("{{ list_items | join(', ') }}")

output = template.render(list_items=['apple', 'banana', 'cherry'])
print(output)  # Output: apple, banana, cherry

6. length

The length filter returns the number of items in a string, list, or any iterable, perfect for quick evaluations within templates.

template = Template("{{ list_items | length }} items available")

output = template.render(list_items=['milk', 'bread', 'eggs'])
print(output)  # Output: 3 items available

7. replace

Utilize the replace filter to substitute occurrences of a substring with another within your data.

template = Template("{{ message | replace('World', 'Jinja') }}")

output = template.render(message="Hello, World!")
print(output)  # Output: Hello, Jinja!

Conclusion

These filters enhance Jinja’s capability to handle and transform data inline effectively, making templates more flexible and powerful. Understanding and utilizing these built-in filters can significantly improve how you build and manage your templates. Explore more Jinja features to further smoothen and optimize your web application's frontend development.

Previous Article: How to remove consecutive whitespace in rendered Jinja pages

Series: Jinja Templates

FastAPI

You May Also Like

  • How to remove consecutive whitespace in rendered Jinja pages
  • How to format large numbers with thousand separators in Jinja template
  • How to format date time in Jinja templates
  • FastAPI + Jinja: How to create custom filters
  • How to pass variables from Python (FastAPI) to Jinja
  • How to decode Jinja response to string
  • How to create and use macros in Jinja
  • How to use namespace in Jinja
  • How to use if/ else in Jinja
  • How to use loops in Jinja
  • FastAPI + SQLAlchemy: Using cursor-based pagination
  • FastAPI: How to use macros in Jinja templates
  • Fixing Common Swagger UI Errors in FastAPI
  • FastAPI Error: 307 Temporary Redirect – Causes and Solutions
  • FastAPI Error: Expected UploadFile, received ‘str’
  • Resolving FastAPI ImportError: No Known Parent Package
  • FastAPI Error: No module named ‘pydantic_core._pydantic_core’
  • Resolving FastAPI 422 Error: Value is not a valid dict
  • Resolving the FastAPI Circular References Error