python flask web开发实战 Jinja2模板

http://jinja.pocoo.org/docs/2.10/templates/#builtin-filters

templates/index.html
<h1>Hello World!</h1>
templates/user.html
<h1>Hello, {{ name }}!</h1>


渲染模板:

from flask import Flask,render_template
@app.route('/')
def index():
return render_template('index.html')
@app.route('/user/<name>')
def user(name):
return render_template('user.html', name=name)


<p>A value from a dictionary: {{ mydict['key'] }}.</p>
<p>A value from a list: {{ mylist[3] }}.</p>
<p>A value from a list, with a variable index: {{ mylist[myintvar] }}.</p>
<p>A value from an object's method: {{ myobj.somemethod() }}.</p>
Hello, {{ name|capitalize }}
name|capitalize
变量过滤:capitalize
safe 不转义
lower
upper
title
trim
striptags


控制语句

{% if user %}
Hello, {{ user }}!
{% else %}
Hello, Stranger!
{% endif %}

<ul>
{% for comment in comments %}
<li>{{ comment }}</li>
{% endfor %}
</ul>

使用宏

{% macro render_comment(comment) %}
<li>{{ comment }}</li>
{% endmacro %}
<ul>
{% for comment in comments %}
{{ render_comment(comment) }}
{% endfor %}
</ul>

包含

{% include 'common.html' %}

block占位符

<html>
<head>
{% block head %}
<title>{% block title %}{% endblock %} - My Application</title>
{% endblock %}
</head>
<body>
{% block body %}
{% endblock %}
</body>
</html>

extends

{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block head %}
{{ super() }}
<style>
</style>
{% endblock %}
{% block body %}
<h1>Hello, World!</h1>
{% endblock %}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容