Generate HTML from HTML template in python?

我的梦境 提交于 2021-02-08 11:49:19

问题


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?


回答1:


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:

<html>
    <head></head>
    <body>
        <p><i>{{ foo }}</i></p>
        <p><b>{{ bar }}</b></p>
    </body>
</html


来源:https://stackoverflow.com/questions/47116572/generate-html-from-html-template-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!