Flask JinJa2模板语法测试


代码1:

DOCTYPE html>
<html>
<head>
    <title>JinJa2 Demotitle>
     <link rel="stylesheet" href="{{url_for('static',filename='bootstrap4/css/bootstrap.css')}}" type="text/css">
head>
<body>
<div class="container mt-2">
<h2>JinJa2 Demoh2>
<h2>{{'abcd'|reverse}}h2>
<h2>{{' abcd ''xxx'}}h2>
<h2>{{' abcd '|trim}}{{'xxx'}}h2>
<h2>{{'aaa''bbb'}}h2>
<h2>{{'aaa'~'bbb'}}h2>
<h2>{{5//2}}h2>
<h2>{{5%2}}h2>
<h2>{{3>1 and 3>4}}h2>
<h2>{{3!=4}}h2>
<h2>{{3 in [3,4,5]}}h2>
<h2>{{'AbCd'|upper}}h2>
<h2>{{'AbCd'|lower}}h2>
<h2>{{'AbCd'|capitalize}}h2>
<h2>{{-3|abs}}h2>
<h2>{{[11,22,33]|first}}h2>
<h2>{{[11,22,33]|last}}h2>
<h2>{{[11,22,33]|sum}}h2>
<h2>{{[44,22,33]|sort}}h2>
<h2>{{[44,22,33]|join("->")}}h2>
<h2>{{123|float}}h2>
<h2>{{12.5|int}}h2>
<h2>{{12.5555|round(2)}}h2>
<h2>{{'123'|float}}h2>
<h2>{{ "%s - %f"|format("Hello?", 123.55555) }}h2>
<h2>
{% set a=1 %}
{% set b=2 %}
{% set c=a+b %}
{{c}}h2>
{% for u in range(1,100,3) %}
<h2>
{{loop.index}}-{{u}}
h2>
{% endfor %}
div>
body>
html>

代码2:

DOCTYPE html>
<html>
<head>
    <title>JinJa2 Demotitle>
     <link rel="stylesheet" href="{{url_for('static',filename='bootstrap4/css/bootstrap.css')}}" type="text/css">
head>
<body>
<div class="container mt-2">
<h2>JinJa2 Demoh2>
{# create a student dict #}
    {% set student=[
        {"name":"zss","age":18,"sex":"女"},
        {"name":"fbb","age":21,"sex":"女"},
        {"name":"mx","age":22,"sex":"男"},
        {"name":"wq","age":20,"sex":"女"}
    ] %}
    <ul>
        {# 对student进行排序,指定attribute为age,降序 #}
        {% for stu in student |sort(attribute="age",reverse=true)%}
            <li>{{ stu.name }} |{{ stu.sex }} li>
        {% endfor %}
    ul>
    <p>------------------------------------------------------p>
    <ul>
        {# 对student进行分组,会返回一个分组后的元组 #}
        {% for stu_list in  student | groupby("sex") %}
            {# 对分组后的元素进行遍历 #}
            {% set idx=loop.index %}
            {% for stu in stu_list.list %}
                <li>
                    {{idx}}-{{loop.index}}-{{ stu.name }} - {{ stu.age }} - {{ stu.sex }}
                li>
            {% endfor %}
        {% endfor %}
    ul>
    <p>------------------------------------------------------p>
    <ul>
        {# 对student进行聚合操作,在将聚合后的元素列表进行拼接 #}
        {{ student | map(attribute="name") | join("<->") }}
    ul>
div>
body>
html>