zoukankan      html  css  js  c++  java
  • jnija2模板渲染

     cat temp.temp
    hello {{ name }}
    
    {% for love in love_sports %}
    my loves sport is {{ love }}
    {% endfor %}
    
    {% if is_boy %}
    i am a good boy
    {% else %}
    i am a good girl
    {% endif %}
    # -*- coding: UTF-8 -*-
    
    from jinja2 import Template
    with open("temp.temp",'r') as f:
        template_content = f.read()
    template = Template(template_content)
    content = template.render(
    name='John Doe',
    love_sports = ["basketall","football","paiball"],
    is_boy=True
    )
    print(content)

    #输出 :

    hello John Doe


    my loves sport is basketall

    my loves sport is football

    my loves sport is paiball

    i am a good boy

    使用 Environment 来初始化对象,并用它来加载模板,

    jinja2支持两种加载模板的方式 

    • PackageLoader:包加载器
    • FileSystemLoader:文件系统加载器
    from jinja2 import Environment, FileSystemLoader
    env = Environment(
        loader = FileSystemLoader('/home/templates')
    )
    
    template = env.get_template('temp.temp')
    content = template.render(
    name='John Doe',
    love_sports = ["basketall","football"],
    is_boy=True
    )
    
    print content
    [root@jinkang-e2elog app]# cat testabcd.py
    from jinja2 import Environment, PackageLoader
    env = Environment(loader=PackageLoader('testabcd','templates'))
    
    template = env.get_template('temp.temp')
    content = template.render(
    name='John Doe',
    love_sports = ["basketall","football"],
    is_boy=True
    )
    
    print content
  • 相关阅读:
    day 7-5 守护线程
    小练习:思考下述代码的执行结果有可能是哪些情况?为什么?
    深浅copy详解
    练习题,使用多线程编写一个简单的文本处理工具
    harbor搭建v1.8.3
    mysql常用命令
    windows安装MySQL
    centos用户和用户组的管理及简单操作
    CentOS 7下安装谷歌浏览器
    typecho管理员修改密码
  • 原文地址:https://www.cnblogs.com/jkklearn/p/13731063.html
Copyright © 2011-2022 走看看