I've got five pages with the same page layout and structure, but some different colors, text, etc, so this is an ideal environment for templating. I've decided to use Jinja2 and probably flask. I've read through the documentation, and some tutorials online, which explain lots about what you can do with templates on a page but not much about how to send variables to the page.
Template variables are defined by the context dictionary passed to the template. You can mess around with the variables in templates provided they are passed in by the application. Variables may have attributes or elements on them you can access too.
Supported Data Types in Jinja Template Jinja has built-in support for all native Python data types, including List, Tuple, Dictionary, Set, String, Integer, Bool, and even Classes.
Here's the basic usage:
First create a template
>>> from jinja2 import Template
>>> template = Template('Hello {{ name }}!')
Then render it passing the variables
>>> template.render(name='John Doe')
u'Hello John Doe!'
Usually you will want to load templates from files instead of code. That's more efficient and optimized, and allows template inheritance:
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('yourapplication', 'templates'))
That will look for templates inside the templates
folder of the yourapplication
Python package, as installed in the Python path. You could use other loaders to load from a specific filesystem or other places too.
Then you can load a template:
template = env.get_template('mytemplate.html')
print template.render(the='variables', go='here')
When using Flask it is all configured for you, so you can just use Flask's render_template
function and it will already look for a templates
subfolder of your application:
from flask import render_template
@app.route('/hello/')
def hello(name=None):
return render_template('hello.html', name=name)
Note the template variable (also known as context) being passed to render_template
Jinja has pretty good documentation. Please read it. Feel free to ask further questions.
Edit: I've googled the interweb in search for an answer and I've found some articles that could help (pretty sure they've helped me)
http://dbanck.de/2009/01/13/using-jinja2-with-django/
http://www.hindsightlabs.com/blog/2010/03/15/jinja2-and-django-4ever/ (dead)
http://djangosnippets.org/snippets/1061/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With