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) -%}
        <input type="{{ type }}" name="{{ name }}" value="{{ value|e }}" size="{{ size }}">
    {%- endmacro %}

    <p>{{ input('username') }}
    <p>{{ input('email') }}
    <p>{{ input('password') }}
    '''

    tm = Template(html)
    msg = tm.render()
    print(msg)

# Вложенные макросы
def test_4():
    html = '''
    {% macro list_users(list_of_user) -%}
    <ul>
    {% for u in list_of_user -%}
        <li>{{u.name}} {{caller(u)}}
    {%- endfor %}
    </ul>
    {%- endmacro %}

    {% call(user) list_users(users) %}
        <ul>
        <li>age: {{user.old}}
        <li>weight: {{user.weight}}
        </ul>
    {% endcall -%}

    '''
    tm = Template(html)
    msg = tm.render(users = persons)
    print(msg)


def main():
    test_4()


if __name__ == '__main__':
    main()