Jinja HTML rendering#

It is very easy to create safe HTML messages using Jinja2 templates. Documentation for template language is available at official jinja web page

To use it you need to create text using Jinja class instead of Format and set proper parse_mode. If you do not want to set default parse mode for whole bot you can set it per-window.

For example you can use environment substitution, cycles and filters:

from aiogram.filters.state import StatesGroup, State

from aiogram_dialog import Window
from aiogram_dialog.widgets.text import Jinja


class DialogSG(StatesGroup):
    ANIMALS = State()


# let's assume this is our window data getter
async def get_data(**kwargs):
    return {
        "title": "Animals list",
        "animals": ["cat", "dog", "my brother's tortoise"]
    }


html_text = Jinja("""
<b>{{title}}</b>
{% for animal in animals %}
* <a href="https://yandex.ru/search/?text={{ animal }}">{{ animal|capitalize }}</a>
{% endfor %}
""")

window = Window(
    html_text,
    parse_mode="HTML",  # do not forget to set parse mode
    state=DialogSG.ANIMALS,
    getter=get_data
)

It will be rendered to this HTML:

<b>Animals list</b>
* <a href="https://yandex.ru/search/?text=cat">Cat</a>
* <a href="https://yandex.ru/search/?text=dog">Dog</a>
* <a href="https://yandex.ru/search/?text=my brother&#39;s tortoise">My brother&#39;s tortoise</a>

In the example above the data from getter is used, but you can also access the data from dialog_data (e.g. {{ dialog_data['user']['weight'] }})

If you want to add custom filters or do some configuration of jinja Environment you can setup it using aiogram_dialog.widgets.text.setup_jinja function