Mercurial > p > roundup > code
comparison roundup/cgi/engine_jinja2.py @ 5015:85484d35f1a2
issue2550811 20% fix: jinja2 template engine now has an example how to use non-ascii unicode contents with a custom filter ('|u').
| author | Bernhard Reiter <bernhard@intevation.de> |
|---|---|
| date | Wed, 06 Jan 2016 22:36:55 +0100 |
| parents | cf22ac054c08 |
| children | 64b05e24dbd8 |
comparison
equal
deleted
inserted
replaced
| 5014:130c82a0ae0a | 5015:85484d35f1a2 |
|---|---|
| 32 """ | 32 """ |
| 33 | 33 |
| 34 import jinja2 | 34 import jinja2 |
| 35 import gettext | 35 import gettext |
| 36 | 36 |
| 37 from types import MethodType | |
| 38 | |
| 37 # http://jinja.pocoo.org/docs/api/#loaders | 39 # http://jinja.pocoo.org/docs/api/#loaders |
| 38 | 40 |
| 39 from roundup.cgi.templating import context, LoaderBase, TemplateBase | 41 from roundup.cgi.templating import context, LoaderBase, TemplateBase |
| 40 | 42 |
| 41 class Jinja2Loader(LoaderBase): | 43 class Jinja2Loader(LoaderBase): |
| 42 def __init__(self, dir): | 44 def __init__(self, dir): |
| 43 extensions = [ | 45 extensions = [ |
| 44 'jinja2.ext.autoescape', | 46 'jinja2.ext.autoescape', |
| 45 ] | 47 ] |
| 46 print "Jinja2 templates: ", dir | 48 print "Jinja2 templates: ", dir |
| 47 print "Extensions: ", extensions | 49 print "Extensions: ", extensions |
| 48 self._env = jinja2.Environment( | 50 self._env = jinja2.Environment( |
| 49 loader=jinja2.FileSystemLoader(dir), | 51 loader=jinja2.FileSystemLoader(dir), |
| 50 extensions=extensions | 52 extensions=extensions |
| 51 ) | 53 ) |
| 54 | |
| 55 # Adding a custom filter that can transform roundup's vars to unicode | |
| 56 # This is necessary because jinja2 can only deal with unicode objects | |
| 57 # and roundup uses utf-8 for the internal representation. | |
| 58 # The automatic conversion will assume 'ascii' and fail sometime. | |
| 59 # Analysed with roundup 1.5.0 and jinja 2.7.1. See issue2550811. | |
| 60 self._env.filters["u"] = lambda s: \ | |
| 61 unicode(s(), "utf-8") if type(s) == MethodType \ | |
| 62 else unicode(s, "utf-8") | |
| 52 | 63 |
| 53 def check(self, tplname): | 64 def check(self, tplname): |
| 54 #print tplname | 65 #print tplname |
| 55 try: | 66 try: |
| 56 #print self._env.get_template(tplname + '.html') | 67 #print self._env.get_template(tplname + '.html') |
