python 模板 html,从python中的HTML模板生成HTML?

I want to design my own HTML template with tags like JSP or Jade and then pass data from python to it and let it generate full html page.

I don't want to construct document at python side like with DOM. Only data goes to page and page tempalte decides, how data lays out.

I don't want to serve resulting pages with HTTP, only generate HTML files.

Is it possible?

UPDATE

I found Jinja2, but I has strange boilerplate requirements. For example, they want me to create environment with

env = Environment(

loader=PackageLoader('yourapplication', 'templates'),

autoescape=select_autoescape(['html', 'xml'])

)

while saying that package yourapplication not found. If I remove loader parameter, it complains on line

template = env.get_template('mytemplate.html')

saying

no loader for this environment specified

Can I just read template from disk and populate it with variables, without extra things?

解决方案

Just use the FileSystemLoader:

import os

import glob

from jinja2 import Environment, FileSystemLoader

# Create the jinja2 environment.

current_directory = os.path.dirname(os.path.abspath(__file__))

env = Environment(loader=FileSystemLoader(current_directory))

# Find all files with the j2 extension in the current directory

templates = glob.glob('*.j2')

def render_template(filename):

return env.get_template(filename).render(

foo='Hello',

bar='World'

)

for f in templates:

rendered_string = render_template(f)

print(rendered_string)

example.j2:

{{ foo }}

{{ bar }}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值