flask中基础模板templates

1.新建manage.py文件

from flask import Flask, render_template, render_template_string, g

from flask_script import Manager

 

app = Flask(__name__)

# 配置自动加载模板文件,调试模式下会自动开启

app.config['TEMPLATES_AUTO_RELOAD'] = True

manager = Manager(app)

 

@app.route('/')

def index():

# return '模板引擎'

# 渲染模板文件

return render_template('index.html')

# 渲染模板字符串

# return render_template_string('<h1>渲染模板字符串</h1>')

 

# 使用变量

@app.route('/var/')

def var():

# g是一个全局的对象,该变量不要分配就可以在模板中使用

# 在一次请求上下文中保持不变

g.name = 'xxx'

# return render_template('var.html', name='goudan')

return render_template_string('<h1>Hello {{g.name}}</h1>')

 

# 使用过滤器

@app.route('/filter/')

def filter():

return render_template('filter.html', name='xiaoming', user='<b>user</b>')

 

# 流程控制

@app.route('/ctrl/')

def ctrl():

return render_template('ctrl.html', name='lucy')

 

# 文件包含

@app.route('/include/')

def include():

return render_template('include1.html')

 

# 宏的使用

@app.route('/macro/')

def macro():

# return render_template('macro.html', name='dahua')

return render_template('macro1.html', name='dahua')

 

# 模板继承

@app.route('/extends/')

def extends():

return render_template('children.html')

 

if __name__ == '__main__':

manager.run()

 

2.各个模板文件

index.html

<h1>模板文件渲染</h1>

 

var.html

{# 注释:变量应该放在两个大括号中 #}

<h1>hello {{ name }}</h1>

<h1>hello {{ g.name }}</h1>

 

ctrl.html

{% if name %}

<h1>Hello {{ name }}!</h1>

{% else %}

<h1>Hello World!</h1>

{% endif %}

 

<ol>

{% for i in range(5) %}

<li>{{ i }}</li>

{% endfor %}

</ol>

 

fliter.html

<h1>Hello {{ name | upper }}</h1>

 

{# 过滤HTML标签 #}

<div>{{ user | striptags }}</div>

 

{# 渲染时不转义 #}

<div>{{ user | safe }}</div>

 

{# 动态开启关闭转义 #}

{% autoescape False %}

<div>{{ user }}</div>

{% endautoescape %}

 

include.html

<h1>这是include1.html中的内容</h1>

{% include 'include2.html' %}

 

include2.html

<div>这是include2.html中的内容</div>

 

macro.html

{# 定义宏 #}

{% macro show_name(name) %}

<h1>Hello {{ name }}!</h1>

{% endmacro %}

{# 调用宏 #}

{{ show_name(name) }}

 

macro1.html

{# 导入宏 #}

{% from 'macro.html' import show_name %}

<h1>这是原有的内容</h1>

{# 调用宏 #}

{{ show_name(name) }}

 

parents.html

<html>

<head>

<meta charset="UTF-8">

<title>{% block title %}基础模板标题{% endblock %}</title>

</head>

<body>

{% block body %}<div>默认内容</div>{% endblock %}

</body>

</html>

 

children.html

{# 继承自另一个模板 #}

{% extends 'parents.html' %}

{# 根据block可以修改原有的block内容 #}

{% block title %}子模板标题{% endblock %}

{% block body %}

{# 保留基础模板中的内容 #}

{{ super() }}

<div>新加的内容</div>

{% endblock %}

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值