##// END OF EJS Templates
templater: make a template a string-only iterator
Dirkjan Ochtman -
r6783:6d824dc8 default
parent child Browse files
Show More
@@ -81,18 +81,18 b' class templater(object):'
81 def __contains__(self, key):
81 def __contains__(self, key):
82 return key in self.cache or key in self.map
82 return key in self.cache or key in self.map
83
83
84 def __call__(self, t, **map):
84 def _template(self, t):
85 '''perform expansion.
85 '''Get the template for the given template name. Use a local cache.'''
86 t is name of map element to expand.
87 map is added elements to use during expansion.'''
88 if not t in self.cache:
86 if not t in self.cache:
89 try:
87 try:
90 self.cache[t] = file(self.map[t]).read()
88 self.cache[t] = file(self.map[t]).read()
91 except IOError, inst:
89 except IOError, inst:
92 raise IOError(inst.args[0], _('template file %s: %s') %
90 raise IOError(inst.args[0], _('template file %s: %s') %
93 (self.map[t], inst.args[1]))
91 (self.map[t], inst.args[1]))
94 tmpl = self.cache[t]
92 return self.cache[t]
95
93
94 def _process(self, tmpl, map):
95 '''Render a template. Returns a generator.'''
96 while tmpl:
96 while tmpl:
97 m = self.template_re.search(tmpl)
97 m = self.template_re.search(tmpl)
98 if not m:
98 if not m:
@@ -119,13 +119,34 b' class templater(object):'
119 lm = map.copy()
119 lm = map.copy()
120 for i in v:
120 for i in v:
121 lm.update(i)
121 lm.update(i)
122 yield self(format, **lm)
122 t = self._template(format)
123 yield self._process(t, lm)
123 else:
124 else:
124 if fl:
125 if fl:
125 for f in fl.split("|")[1:]:
126 for f in fl.split("|")[1:]:
126 v = self.filters[f](v)
127 v = self.filters[f](v)
127 yield v
128 yield v
128
129
130 def __call__(self, t, **map):
131 '''Perform expansion. t is name of map element to expand. map contains
132 added elements for use during expansion. Is a generator.'''
133 tmpl = self._template(t)
134 iters = [self._process(tmpl, map)]
135 while iters:
136 try:
137 item = iters[0].next()
138 except StopIteration:
139 iters.pop(0)
140 continue
141 if isinstance(item, str):
142 yield item
143 elif item is None:
144 yield ''
145 elif hasattr(item, '__iter__'):
146 iters.insert(0, iter(item))
147 else:
148 yield str(item)
149
129 def templatepath(name=None):
150 def templatepath(name=None):
130 '''return location of template file or directory (if no name).
151 '''return location of template file or directory (if no name).
131 returns None if not found.'''
152 returns None if not found.'''
General Comments 0
You need to be logged in to leave comments. Login now