diff options
author | Joshua Harlow <harlowja@gmail.com> | 2014-03-02 20:37:27 -0800 |
---|---|---|
committer | Joshua Harlow <harlowja@gmail.com> | 2014-03-02 20:37:27 -0800 |
commit | 3f3450660f5f7118ac0583de5d137120c1ae4abd (patch) | |
tree | 3662863b7b845b4a2f476cdd22c108f04d7e91c3 | |
parent | acfd6c50e4dc3de5e20cfabe6bac1569e43d3ff1 (diff) | |
download | vyos-cloud-init-3f3450660f5f7118ac0583de5d137120c1ae4abd.tar.gz vyos-cloud-init-3f3450660f5f7118ac0583de5d137120c1ae4abd.zip |
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.
-rw-r--r-- | cloudinit/templater.py | 32 | ||||
-rw-r--r-- | requirements.txt | 1 |
2 files changed, 31 insertions, 2 deletions
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 <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_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) diff --git a/requirements.txt b/requirements.txt index fdcbd143..2b010075 100644 --- a/requirements.txt +++ b/requirements.txt @@ -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 |