开发者

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 o开发者_如何学JAVAnline, 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?


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜