开发者

Sharing Jinja2 templates between Pylons and Django applications

I'm writing a couple of Jinja2 templates that basically implement some common grid layouts. I'd like to be able to share this 'library' of templates between a Pylons app and Django app.

I've hit a minor stumbling block in that Django's template context is accessible from the "top-level" of the template, whereas Pylons wraps your context inside the thread local c (or tmpl_context) variable.

Here are some analogous examples that demonstrate this.

Django

from django.shortcuts import render_to_response

ctx = {}
ctx['name'] = 'John'

return render_to_response('hello.html', ctx)

hello.html:

Hello {{ name }}

Pylons

from pylons import tmpl_context as c
from myapp.lib.base import render

c.name = 'John'
return render('hello.html') 

hello.html:

Hello {{ c.name }}

What I'm trying to do is make it so that hello.html is the same across both 开发者_JS百科frameworks.

One way I see to do it is by wrapping the Django render_to_response and do something like this:

ctx['c'] = ctx

But that just doesn't feel right. Anybody see other alternatives to this?

Thanks


How dated is your version of Pylons? render seems to be deprecated in favor of render_jinja2. Granted, the Jinja2 documentation mislabels it as render_jinja, and the Pylons documentation doesn't show it at all, but the Pylons 1.0 source code does include it and imply its usage.

Or if you're stuck with an older version of Pylons, you can exploit the fact that setting c.name is the same as setting c.__dict__['name'], and similarly for all its attributes. This makes it easy to set all of c's attributes if you have the ctx dict handy.

ctx = {'name': 'John'}

# Django
from django.shortcuts import render_to_response
render_to_response('hello.html', ctx)

# old Pylons?
from pylons import tmpl_context as c
from pylons.templating import render
c.__dict__.update(ctx)
render('hello.html')

# new Pylons
from pylon.templating import render_jinja2
render_jinja2('hello.html', ctx)

Also, I'm surprised that the old Pylons named the variable in the template based on what you named the object that you imported. Are you sure that c isn't passed as an argument to render?

Disclaimer: I don't have Django or Pylons installed, so I can't test either of my suggestions.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜