渲染模板与控制结构
hello3.py
# -*- coding: cp936 -*-
import os
import sys
import logging.config
import flask
import socket
from flask import Flask,jsonify
from flask import request
from flask import render_template
app = Flask(__name__)
@app.route('/')
def index():
return '<h1>Helloo World!</h1>'
@app.route('/user/<username>')
def user(username):
#不用写成D:\python27\flasks\templates\user.html格式 虽然是D:\python27\flasks\hello3.py
return render_template('user.html',name=username)
if __name__ == "__main__":
ip='0.0.0.0'
app.run( host=ip,port=5000,debug=False )
user.html:
<h1>helloo,{{name|capitalize}}!</h1>
{% if name %}
Hello,{{name}}
{% else %}
Hello,Stranger!
{% endif %}
宏
hello3.py
import os
import sys
import logging.config
import flask
import socket
from flask import Flask,jsonify
from flask import request
from flask import render_template
app = Flask(__name__)
@app.route('/')
def index():
return '<h1>Helloo World!</h1>'
@app.route('/user/<username>')
def user(username):
#不用写成D:\python27\flasks\templates\user.html格式 虽然是D:\python27\flasks\hello3.py
return render_template('user.html',name=username)
#宏使用
@app.route('/comment')
def com():
comments=['1','2','3']
return render_template('comments.html',comments=comments)
if __name__ == "__main__":
ip='0.0.0.0'
app.run( host=ip,port=5000,debug=False )
comment.html
<!-- 模板中使用for渲染-->
<ul>
{% for comment in comments %}
<li>{{comment}}</li>
{% endfor %}
</ul>
<br>
<hr>
<br>
<!-- Jinja2中的宏 类似函数-->
{% macro render_comment(comment)%}
<li>{{comment}}</li>
{% endmacro %}
<ul>
{% for comment in comments %}
{{render_comment(comment)}}
{% endfor %}
</ul>
继承
#继承使用
@app.route('/extends')
def ext():
return render_template('extendsBase.html')
base.html:
<html>
<head>
{% block head %}
<title> {% block title%}{%endblock%}-My Application</title>
{% endblock %}
</head>
<body>
{% block body %}
{% endblock %}
</body>
</html>
extendsBase.html:
{% extends 'base.html' %}
{% block title %}Index{%endblock%}
{%block head%}
{{super()}}
<style>
</style>
{%endblock%}
{%block body%}
<h1>Hello,Extends!</h1>
{%endblock%}
敲代码~开心~