from jinja2 import Template cars = [ {'model': 'Ауди', 'price': 23000}, {'model': 'Шкода', 'price': 17300}, {'model': 'Вольво', 'price': 44300}, {'model': 'Фольксваген', 'price': 21300}, ] ''' sum(iterable, attribute=None, start=0) max ''' def test_1(): # tpl = "{{ cs }}" # просто выводит коллекцию # tpl = "Суммарная цена автомобилей {{ cs | sum(attribute='price') }}" # tpl = "Автомобиль с максимальной ценой {{ (cs | max(attribute='price')).model }}" # Случайный автомобиль # tpl = "Автомобиль: {{ cs | random }}" # Замена символов tpl = "Автомобиль: {{ cs | replace('о', 'О') }}" tm = Template(tpl) msg = tm.render(cs = cars) print(msg) ''' Применение фильтров внутри шаблонов ''' persons = [ {"name": "Алексей", "old": 18, "weight": 78.5}, {"name": "Николай", "old": 28, "weight": 82.5}, {"name": "Иван", "old": 33, "weight": 94.0} ] def test_2(): tpl = ''' {%- for u in users -%} {% filter upper %}{{u.name}}{% endfilter %} {% endfor -%} ''' tm = Template(tpl) msg = tm.render(users = persons) print(msg) # Макросы и вложенные макросы def test_3(): html = ''' {% macro input(name, value='', type='text', size=20) -%} {%- endmacro %}
{{ input('username') }}
{{ input('email') }}
{{ input('password') }} ''' tm = Template(html) msg = tm.render() print(msg) # Вложенные макросы def test_4(): html = ''' {% macro list_users(list_of_user) -%}