flask-宏\import--include和set

模板做的宏跟python中的函数类似,可以传递参数,但是不能有返回值,可以将一些经常用到的代码片段放到宏中,然后把一些不固定的值抽取出来当成一个变量。

{% macro input(name, value='',type='text') %}
	<input type="{{ type }}" name="{{ name }}" value="{{ value }}"
	{ % endmacro %}

以上例子可以抽取了一个input标签,指定了一些默认参数。那么我们以后创建input标签的时候,可以通过它快速的创建:

<p>{{ input('username') }}</p>
<p>{{ input('password',type='password') }}</p>

代码:

<table>
    <tr>
        <td>用户名:</td>
        <td>{{ input('username') }}</td>
    </tr>
    <tr>
        <td>密码:</td>
        <td>{{ input('password', type='password')}}</td>
    </tr>
    <tr>
        <td>提交:</td>
        <td>{{ input(value='提交', type='submit') }}</td>
    </tr>
</table>

import语句

在真是的开发中,会将一些常用的宏单独放在一个文件中,在需要的时候,再从这个文件中进行导入。import语句的用法跟python中的import类似,可以直接import…as…,也可以from…import…或者from…import…as…,假设现在有一个文件,叫做form.html,里面有两个宏分别为input和textarea。
第一种传参方式:

{% import 'marco.html' as macro %}
{{ macro.input('username', value="用户名") }}

<!--有参数传入时,加上with context-->
<!--{% import 'marco.html' as macro with context%}-->

第二种传参方式:

<!--{% from "marco.html" import input %}-->
{{ input('password', type="password")}}

include 和set语句

include语句
include语句可以把一个模板引入到另外一个模板中,类似于把一个模板的代码 到另外一个模板的指定位置。

{% include 'header.html' %}
	主体内容
{% include 'footer.html' %}

代码实例:
header.html:

<ul>
    <li>新闻</li>
    <li>娱乐</li>
    <li>图片</li>
    <li>女人</li>
</ul>

footer.html:

<footer>
    这是网站底部
</footer>

detail.html:

{% include 'commit/header.html' %}
    <h1>这是我的详情页</h1>
{% include 'commit/footer.html' %}
@app.route('/detail/')
def detail() 
	return render_template("commit/detail.html") # 路径

赋值(set)语句
有时候我们想再模板中添加变量,这时候赋值语句(set)就排上用场了。

{% set name= 'happy' %}

那么以后就可以使用name来代替happy这个值了,同时,也可以给他赋值为列表和元组:

{% set navigation = [('index.html', 'Index'), ('about.html', 'About')] %}

赋值语句创建的变量再其之后都是有效的,如果不想让一个变量污染全局环境,可以使用with语句来创建一个内部域,将set语句放在其中,这样创建的变量只在with代码块中才有效

{% with %}
    {% set name = '这是局部' %}
    {{ name }}
{% endwith %}

{% with foo=44 %}
    <p>{{ foo }}</p>
{% endwith %}
<!--可以定义字典-->
{% with fo={"name": "happy"} %}
    <p>{{ fo }}</p>
{% endwith %}

<!--可以定义列表  也可循环-->
{% with fd=[1,2,3] %}
    {% for f in fd %}
    <p>{{ f }}</p>
    {% endfor %}
{% endwith %}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值