• 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
  • 相关阅读:
    货币系统
    纸牌
    活动
    KKT-黑白球
    POJ2676-Sudoku
    POJ1717-Dominoes
    POJ1088-滑雪
    POJ1862-Stripies
    POJ2531-Network Saboteur
    2019.12.13 数的划分
  • 原文地址:https://www.cnblogs.com/jkklearn/p/13731063.html
Copyright © 2020-2023  润新知