Jinja2¶
Jinja2 is a modern and designer friendly templating language for Python, modelled after Django’s templates. It is fast, widely used and secure with the optional sandboxed template execution environment:
1 2 3 4 5 6 | <title>{% block title %}{% endblock %}</title>
<ul>
{% for user in users %}
<li><a href="{{ user.url }}">{{ user.username }}</a></li>
{% endfor %}
</ul>
|
Why ?¶
Zunzuncito was made mainly for responding in json format not HTML, but also one of the design goals is to give the ability to create almost anything easy, therefor if you need to display HTML, Jinja2 integrates very easy.
Example¶
The following code, handles the request for: http://api.zunzun.io/jinja2.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | import os
from jinja2 import Environment, FileSystemLoader
from zunzuncito import tools
jinja = Environment(autoescape=True, loader=FileSystemLoader(
os.path.join(os.path.abspath(os.path.dirname(__file__)), 'templates')))
class APIResource(object):
def __init__(self):
self.headers['Content-Type'] = 'text/html; charset=UTF-8'
def dispatch(self, request, response):
request.log.debug(tools.log_json({
'API': request.version,
'method': request.method,
'URI': request.URI,
'vroot': request.vroot
}, True))
response.headers.update(self.headers)
template_values = {
'IP': request.environ.get('REMOTE_ADDR', 0)
}
template = jinja.get_template('example.html')
return template.render(template_values).encode('utf-8')
|
The example.html contains:
1 2 3 4 5 6 7 8 9 10 | <html>
<head>
<meta charset="utf-8">
<title>{{ IP }}</title>
</head>
<body>
<h3>IP: {{ IP }}</h3>
</body>
</html>
|
Directory structure¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | /home/
`--zunzun/
|--app.py
`--my_api
|--__init__.py
`--default
|--__init__.py
`--v0
|--__init__.py
`--zun_jinja2
|--__init__.py
|--zun_jinja2.py
`--templates
`--example.html
|
See also
A great amount of time has been spent creating, crafting and maintaining this software, please consider donating.
Donating helps ensure continued support, development and availability.
comments powered by Disqus