From 3f3450660f5f7118ac0583de5d137120c1ae4abd Mon Sep 17 00:00:00 2001 From: Joshua Harlow Date: Sun, 2 Mar 2014 20:37:27 -0800 Subject: Allow the usage of mako templates Mako is a python 2.6->3.x compatible templating engine, allow its optional usage (until we can depricate cheetah) by allowing for specifying a template file header that can define which template engine to use. For now support cheetah (the default) and if specified support mako as well. --- cloudinit/templater.py | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) (limited to 'cloudinit/templater.py') diff --git a/cloudinit/templater.py b/cloudinit/templater.py index 77af1270..a7527964 100644 --- a/cloudinit/templater.py +++ b/cloudinit/templater.py @@ -20,10 +20,37 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -from Cheetah.Template import Template +import re +from Cheetah.Template import Template as CTemplate +from mako.template import Template as MTemplate + +from cloudinit import log as logging from cloudinit import util +LOG = logging.getLogger(__name__) +DEF_RENDERER = (lambda content, params: + CTemplate(content, searchList=[params]).respond()) +RENDERERS = { + 'mako': lambda content, params: MTemplate(content).render(**params), + 'cheetah': DEF_RENDERER, +} +TYPE_MATCHER = re.compile(r"##\s*template:(.*)", re.I) + + +def detect_template(text): + lines = text.splitlines() + if not lines: + return DEF_RENDERER + line = lines[0] + type_match = TYPE_MATCHER.match(line) + if not type_match: + return DEF_RENDERER + template_type = type_match.group(1).lower().strip() + if template_type not in RENDERERS: + LOG.warn("Unknown template type requested: %s", template_type) + return RENDERERS.get(template_type, DEF_RENDERER) + def render_from_file(fn, params): return render_string(util.load_file(fn), params) @@ -37,4 +64,5 @@ def render_to_file(fn, outfn, params, mode=0644): def render_string(content, params): if not params: params = {} - return Template(content, searchList=[params]).respond() + renderer = detect_template(content) + return renderer(content, params) -- cgit v1.2.3