filter.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. from jinja2 import Template
  2. cars = [
  3. {'model': 'Ауди', 'price': 23000},
  4. {'model': 'Шкода', 'price': 17300},
  5. {'model': 'Вольво', 'price': 44300},
  6. {'model': 'Фольксваген', 'price': 21300},
  7. ]
  8. '''
  9. sum(iterable, attribute=None, start=0)
  10. max
  11. '''
  12. def test_1():
  13. # tpl = "{{ cs }}" # просто выводит коллекцию
  14. # tpl = "Суммарная цена автомобилей {{ cs | sum(attribute='price') }}"
  15. # tpl = "Автомобиль с максимальной ценой {{ (cs | max(attribute='price')).model }}"
  16. # Случайный автомобиль
  17. # tpl = "Автомобиль: {{ cs | random }}"
  18. # Замена символов
  19. tpl = "Автомобиль: {{ cs | replace('о', 'О') }}"
  20. tm = Template(tpl)
  21. msg = tm.render(cs = cars)
  22. print(msg)
  23. '''
  24. Применение фильтров внутри шаблонов
  25. '''
  26. persons = [
  27. {"name": "Алексей", "old": 18, "weight": 78.5},
  28. {"name": "Николай", "old": 28, "weight": 82.5},
  29. {"name": "Иван", "old": 33, "weight": 94.0}
  30. ]
  31. def test_2():
  32. tpl = '''
  33. {%- for u in users -%}
  34. {% filter upper %}{{u.name}}{% endfilter %}
  35. {% endfor -%}
  36. '''
  37. tm = Template(tpl)
  38. msg = tm.render(users = persons)
  39. print(msg)
  40. # Макросы и вложенные макросы
  41. def test_3():
  42. html = '''
  43. {% macro input(name, value='', type='text', size=20) -%}
  44. <input type="{{ type }}" name="{{ name }}" value="{{ value|e }}" size="{{ size }}">
  45. {%- endmacro %}
  46. <p>{{ input('username') }}
  47. <p>{{ input('email') }}
  48. <p>{{ input('password') }}
  49. '''
  50. tm = Template(html)
  51. msg = tm.render()
  52. print(msg)
  53. # Вложенные макросы
  54. def test_4():
  55. html = '''
  56. {% macro list_users(list_of_user) -%}
  57. <ul>
  58. {% for u in list_of_user -%}
  59. <li>{{u.name}} {{caller(u)}}
  60. {%- endfor %}
  61. </ul>
  62. {%- endmacro %}
  63. {% call(user) list_users(users) %}
  64. <ul>
  65. <li>age: {{user.old}}
  66. <li>weight: {{user.weight}}
  67. </ul>
  68. {% endcall -%}
  69. '''
  70. tm = Template(html)
  71. msg = tm.render(users = persons)
  72. print(msg)
  73. def main():
  74. test_4()
  75. if __name__ == '__main__':
  76. main()