← Back to team overview

cloud-init-dev team mailing list archive

[Merge] lp:~harlowja/cloud-init/changeable-templates into lp:cloud-init

 

Joshua Harlow has proposed merging lp:~harlowja/cloud-init/changeable-templates into lp:cloud-init.

Requested reviews:
  cloud init development team (cloud-init-dev)

For more details, see:
https://code.launchpad.net/~harlowja/cloud-init/changeable-templates/+merge/208994

Allow the usage of mako templates

Mako is a python 2.4->3.x compatible
templating engine, allow its optional
usage (until we can depreciate 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.

-- 
https://code.launchpad.net/~harlowja/cloud-init/changeable-templates/+merge/208994
Your team cloud init development team is requested to review the proposed merge of lp:~harlowja/cloud-init/changeable-templates into lp:cloud-init.
=== modified file 'cloudinit/templater.py'
--- cloudinit/templater.py	2012-07-09 20:41:45 +0000
+++ cloudinit/templater.py	2014-03-03 04:40:55 +0000
@@ -20,10 +20,37 @@
 #    You should have received a copy of the GNU General Public License
 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-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_string(content, params):
     if not params:
         params = {}
-    return Template(content, searchList=[params]).respond()
+    renderer = detect_template(content)
+    return renderer(content, params)

=== modified file 'requirements.txt'
--- requirements.txt	2014-02-12 10:14:49 +0000
+++ requirements.txt	2014-03-03 04:40:55 +0000
@@ -2,6 +2,7 @@
 
 # Used for untemplating any files or strings with parameters.
 cheetah
+mako
 
 # This is used for any pretty printing of tabular data.
 PrettyTable


Follow ups