flask jinja2 语法——变量、控制结构及模板继承

##   jinja.py

<!DOCTYPE html>
<html lang="en">
<head>
{% block head %}
<meta charset="UTF-8">
<title>Welcome</title>
{% endblock %}
</head>
<body>
<header>{% block header %}{% endblock %}</header>
<div>{% block content %}{% endblock %}</div>

{#{% for item in items %}#}
{# <li>{% block loop_item scoped %}{{ item }}{% endblock %}</li>#}
{#{% endfor %}#}
<footer>
{% block footer %}
Copyright 2018 by <a href="www.baidu.com">baidu</a>
{% endblock %}
</footer>
</body>
</html>
-----------------------------------------------------------------------------------------------------------


##  index.html

{#<!DOCTYPE html>#}
{#<html lang="en">#}
{#<head>#}
{# <meta charset="UTF-8">#}
{# <title>welcome</title>#}
{#</head>#}
{# <body>
{#{{ title|safe }}#}
{#</body> #}
{% extends 'base.html' %}
{% import '_macros.html' as ui %}
{#{% macro input(name, value='', type='text', size=20) %}#}
{# <input type="{{ type }}"#}
{# name="{{ name }}"#}
{# value="{{ value }}"#}
{# size="{{ size }}"#}
{# />#}
{#{% endmacro %}#}
{% block title %}{{ title }}{% endblock %}
{% block content %}
{% set links=[
{'label':'index', 'href':url_for('.index')},
{'label':'about', 'href':url_for('.about')},
{'label':'login', 'href':url_for('.login')},
] %}
<nav>
{% for link in links %}
{# {% if loop.index is odd %} | {% endif %}#}
{% if not loop.first %} | {% endif %}
<a href="{{ link.href }}">{{ link.label }}</a>
{% endfor %}
</nav>
<h1>{{ self.title() }}</h1>

{{ ui.input('username') }}
{{ ui.input('password', type='password') }}
{% endblock content %}
{% block footer %}
<hr>
{{ super() }}
{% endblock %}

{#</html>#}

--------------------------------------------------------------------------
##  base.html
<!DOCTYPE html>
<html lang="en">
<head>
{% block head %}
<meta charset="UTF-8">
<title>Welcome</title>
{% endblock %}
</head>
<body>
<header>{% block header %}{% endblock %}</header>
<div>{% block content %}{% endblock %}</div>

{#{% for item in items %}#}
{# <li>{% block loop_item scoped %}{{ item }}{% endblock %}</li>#}
{#{% endfor %}#}
<footer>
{% block footer %}
Copyright 2018 by <a href="www.baidu.com">baidu</a>
{% endblock %}
</footer>
</body>
</html>
---------------------------------------------------------------------------------
_macros.html
{% macro input(name, value='', type='text', size=20) %}
<input type="{{ type }}"
name="{{ name }}"
value="{{ value }}"
size="{{ size }}"
/>
{% endmacro %}



原文地址:https://www.cnblogs.com/pontoon/p/8598649.html