DocumentationAPI Reference📓 Tutorials🧑‍🍳 Cookbook🤝 Integrations💜 Discord🎨 Studio (Waitlist)
Documentation

Jinja Templates

Learn how Jinja templates work with Haystack components.

Jinja templates are text structures that contain placeholders for generating dynamic content. These placeholders are filled in when the template is rendered. You can check out the full list of Jinja2 features in the original documentation.

You can use these templates in Haystack Builders, OutputAdapter, and ConditionalRouter components.

Here is an example of OutputAdapter using a short Jinja template to output only the content field of the first document in the arrays of documents:

from haystack import Document
from haystack.components.converters import OutputAdapter

adapter = OutputAdapter(template="{{ documents[0].content }}", output_type=str)
input_data = {"documents": [Document(content="Test content")]}
expected_output = {"output": "Test content"}
assert adapter.run(**input_data) == expected_output

Safety Features

Due to how we use Jinja in some Components, there are some security considerations to take into account. Jinja works by executing embedded in templates, so it’s imperative that they stem from a trusted source. If the template is allowed to be customized by the end user, it can potentially lead to remote code execution.

To mitigate this risk, Jinja templates are executed and rendered in a sandbox environment. While this approach is safer, it's also less flexible and limits the expressiveness of the template. If you need the more advanced functionality of Jinja templates, components that use them provide an unsafe init parameter - setting it to False will disable the sandbox environment and enable unsafe template rendering.

With unsafe template rendering, the OutputAdapter and ConditionalRouter components allow their output_type to be set to one of the Haystack data classes such as ChatMessageDocument, or Answer.