Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code

Unified Diff: cms/converters.py

Issue 5521995252891648: Issue 2180 - [cms] Add support for custom Jinja2 functions (Closed)
Patch Set: Generalized to all globals Created March 20, 2015, 4:01 p.m.
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
View side-by-side diff with in-line comments
Download patch
« no previous file with comments | « README.md ('k') | no next file » | no next file with comments »
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
Index: cms/converters.py
===================================================================
--- a/cms/converters.py
+++ b/cms/converters.py
@@ -263,31 +263,33 @@ class TemplateConverter(Converter):
"linkify": self.linkify,
"toclist": self.toclist,
}
globals = {
"get_string": self.get_string,
}
- for filename in self._params["source"].list_files("filters"):
- root, ext = os.path.splitext(filename)
- if ext.lower() != ".py":
- continue
+ for dirname, dictionary in [("filters", filters), ("globals", globals)]:
+ for filename in self._params["source"].list_files(dirname):
+ root, ext = os.path.splitext(filename)
+ if ext.lower() != ".py":
+ continue
- path = "%s/%s" % ("filters", filename)
- code = self._params["source"].read_file(path)
- module = imp.new_module(root.replace("/", "."))
- exec code in module.__dict__
+ path = "%s/%s" % (dirname, filename)
+ code = self._params["source"].read_file(path)
+ module = imp.new_module(root.replace("/", "."))
+ exec code in module.__dict__
- func = os.path.basename(root)
- if not hasattr(module, func):
- raise Exception("Expected function %s not found in filter file %s" % (func, filename))
- filters[func] = getattr(module, func)
- filters[func].module_ref = module # Prevent garbage collection
+ name = os.path.basename(root)
+ if not hasattr(module, name):
+ raise Exception("Expected symbol %s not found in %s file %s" % (name, dirname, filename))
+ dictionary[name] = getattr(module, name)
+ if hasattr(dictionary[name], "__call__"):
Sebastian Noack 2015/03/20 16:10:54 You might want to use the callable() built-in func
Wladimir Palant 2015/03/20 16:21:12 A function doesn't usually have a reference to its
Sebastian Noack 2015/03/20 16:26:54 Yeah, this actually make sense, since we create th
Wladimir Palant 2015/03/20 16:42:50 Done.
+ dictionary[name].module_ref = module # Prevent garbage collection
self._env = jinja2.Environment(loader=self._SourceLoader(self._params["source"]), autoescape=True)
self._env.filters.update(filters)
self._env.globals.update(globals)
def get_html(self, source):
template = self._env.from_string(source)
module = template.make_module(self._params)
« no previous file with comments | « README.md ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld