I need to render HTML page using jinja but without flask I read some other questions here but none had clear answer kindly let me know how can i achieve the same
File structre 1.py HTML folder 1.html templates show persons.txt
Here I need to render 1.html using 1.py – is it possble to do it in ofline mode
current 1.py
from jinja2 import Environment, FileSystemLoader
persons = [
{'name': 'Andrej', 'age': 34},
{'name': 'Mark', 'age': 17},
{'name': 'Thomas', 'age': 44},
{'name': 'Lucy', 'age': 14},
{'name': 'Robert', 'age': 23},
{'name': 'Dragomir', 'age': 54}
]
file_loader = FileSystemLoader('templates')
env = Environment(loader=file_loader)
template = env.get_template('show persons.txt')
template = env.get_template('1.html ') # how can i do the same with html here
output = template.render(persons=persons)
print(output)
currently with this I am able to print output but if I need to get same data on a html file what can be done here ?
Also if possible if also can we open the html page when run
updated code after Corralien comments is der a way to open this in browser directly
from jinja2 import Environment, FileSystemLoader
persons = [
{'name': 'Andrej', 'age': 34},
{'name': 'Mark', 'age': 17},
{'name': 'Thomas', 'age': 44},
{'name': 'Lucy', 'age': 14},
{'name': 'Robert', 'age': 23},
{'name': 'Dragomir', 'age': 54}
]
file_loader = FileSystemLoader('templates')
env = Environment(loader=file_loader)
template = env.get_template('1.html')
output = template.render(persons=persons)
print(output)
Output
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
Andrej - 34
Mark - 17
Thomas - 44
Lucy - 14
Robert - 23
Dragomir - 54
</body>
</html>
Advertisement
Answer
To open your html file into your browser, use webbrowser module (standard library)
import webbrowser
import tempfile
# Your code here
...
output = template.render(persons=persons)
with open('output.html', 'w') as fp:
fp.write(output)
webbrowser.open_new('output.html') # or .open_new_tab('output.html')