Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do you store the variables in jinja?

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.

  • Where do you store the page-specific variables?
  • How does the code know which page has been requested and which variables to load?
like image 383
Kevin Burke Avatar asked Jan 12 '11 01:01

Kevin Burke


People also ask

How are variables in Jinja2 templates specified?

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.

Which data type we use for send values in Jinja?

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.


2 Answers

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.

like image 142
nosklo Avatar answered Sep 21 '22 00:09

nosklo


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/

like image 42
StefanNch Avatar answered Sep 22 '22 00:09

StefanNch