Skip to content

Commit

Permalink
[#2501] custom snippet tag added
Browse files Browse the repository at this point in the history
  • Loading branch information
tobes committed Jun 8, 2012
1 parent f56ce8a commit 253267a
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
4 changes: 3 additions & 1 deletion ckan/config/environment.py
Expand Up @@ -21,6 +21,8 @@
import ckan.lib.app_globals as app_globals


import lib.jinja_tags

# Suppress benign warning 'Unbuilt egg for setuptools'
warnings.simplefilter('ignore', UserWarning)

Expand Down Expand Up @@ -193,7 +195,7 @@ def template_loaded(template):
env = config['pylons.app_globals'].jinja_env = Environment(
loader=PackageLoader('ckan', 'templates'),
autoescape=True,
extensions=['jinja2.ext.i18n', 'jinja2.ext.do']
extensions=['jinja2.ext.i18n', 'jinja2.ext.do', lib.jinja_tags.SnippetExtension]
)
env.install_gettext_callables(_, N_, newstyle=True)
config['pylons.app_globals'].jinja_env = env
Expand Down
42 changes: 42 additions & 0 deletions ckan/lib/jinja_tags.py
@@ -0,0 +1,42 @@
from jinja2 import nodes
from jinja2.ext import Extension

import lib.base as base


class SnippetExtension(Extension):
''' Custom snippet tag
{% snippet template_name> [, <keyword>=<value>].. %}
This is mostly magic..
'''

tags = set(['snippet'])

def parse(self, parser):
stream = parser.stream
tag = stream.next()
template_name = parser.parse_expression()
# get keywords
kwargs = []
while not stream.current.test_any('block_end'):
stream.expect('comma')
if stream.current.test('name') and stream.look().test('assign'):
key = nodes.Const(stream.next().value)
stream.skip()
value = parser.parse_expression()
kwargs.append(nodes.Pair(key, value, lineno=key.lineno))

def make_call_node(*kw):
return self.call_method('_render', args=[
template_name,
nodes.Dict(kwargs),
], kwargs=kw)

return nodes.Output([make_call_node()]).set_lineno(tag.lineno)

@classmethod
def _render(cls, template_name, kwargs):
return base.render_snippet(template_name, **kwargs)

0 comments on commit 253267a

Please sign in to comment.