blob: 947150d30009c245c01d1a69cec9310edf20b6f7 [file] [log] [blame]
Armin Ronacher05530932008-04-20 13:27:49 +02001# -*- coding: utf-8 -*-
2"""
3 jinja2.ext
4 ~~~~~~~~~~
5
6 Jinja extensions (EXPERIMENAL)
7
8 The plan: i18n and caching becomes a parser extension. cache/endcache
9 as well as trans/endtrans are not keyword and don't have nodes but
10 translate into regular jinja nodes so that the person who writes such
11 custom tags doesn't have to generate python code himself.
12
13 :copyright: Copyright 2008 by Armin Ronacher.
14 :license: BSD.
15"""
16from jinja2 import nodes
17
18
19class Extension(object):
20 """Instances of this class store parser extensions."""
21
22 #: if this extension parses this is the list of tags it's listening to.
23 tags = set()
24
25 def __init__(self, environment):
26 self.environment = environment
27
28 def update_globals(self, globals):
29 """Called to inject runtime variables into the globals."""
30 pass
31
32 def parse(self, parser):
33 """Called if one of the tags matched."""
34
35
36class CacheExtension(Extension):
Armin Ronacher2b60fe52008-04-21 08:23:59 +020037 """An example extension that adds cacheable blocks."""
Armin Ronacher05530932008-04-20 13:27:49 +020038 tags = set(['cache'])
39
40 def parse(self, parser):
41 lineno = parser.stream.next().lineno
42 args = [parser.parse_expression()]
Armin Ronacher4f7d2d52008-04-22 10:40:26 +020043 if parser.stream.current.type is 'comma':
44 parser.stream.next()
Armin Ronacher05530932008-04-20 13:27:49 +020045 args.append(parser.parse_expression())
46 body = parser.parse_statements(('name:endcache',), drop_needle=True)
47 return nodes.CallBlock(
Armin Ronacher4f7d2d52008-04-22 10:40:26 +020048 nodes.Call(nodes.Name('cache_support', 'load'), args, [], None, None),
Armin Ronacher05530932008-04-20 13:27:49 +020049 [], [], body
50 )