Skip to content

Instantly share code, notes, and snippets.

@PSJoshi
Last active August 29, 2015 14:17
Show Gist options
  • Save PSJoshi/5acf8168c22d64b2fd45 to your computer and use it in GitHub Desktop.
Save PSJoshi/5acf8168c22d64b2fd45 to your computer and use it in GitHub Desktop.
python-jinja example
#!/usr/bin/env python
import os
from jinja2 import Environment, FileSystemLoader
dir_path = os.path.dirname(os.path.abspath(__file__))
t_environment = Environment(
autoescape=False,
#loader=FileSystemLoader(os.path.join(dir_path, 'templates')),
loader=FileSystemLoader(os.path.dirname(os.path.abspath(__file__))),
trim_blocks=False)
def html_output(output_filename,template_filename,context=None):
context = {
'urls':['http://www.google.com','http://www.yahoo.com','http://www.bing.com'],
'name':'Joshi P S'
}
output = t_environment.get_template(template_filename).render(context)
with open(output_filename,'w') as f:
f.write(output)
if __name__=="__main__":
html_output('jinja_test.html','test_template.html')
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Jinja example</title>
</head>
<body>
<center>
<h1>Jinja Example</h1>
<p>{{ urls|length }} links</p>
</center>
<ol align="left">
{% for url in urls -%}
<li><a href="{{ url }}">{{ url }}</a></li>
{% endfor -%}
</ol>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment