2

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?

asked Nov 4, 2017 at 23:15

1 Answer 1

6

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>
adhg
11k13 gold badges63 silver badges99 bronze badges
answered Nov 5, 2017 at 0:16
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.