]>
Commit | Line | Data |
---|---|---|
35681c06 | 1 | #!/usr/bin/env python3 |
904908bc | 2 | # |
d486dd0d | 3 | # Copyright 2014-2017 Cumulus Networks, Inc. All rights reserved. |
904908bc RP |
4 | # Author: Roopa Prabhu, roopa@cumulusnetworks.com |
5 | # | |
6 | # template -- | |
7 | # helper class to render templates | |
8 | # | |
14dc390d | 9 | |
d486dd0d JF |
10 | try: |
11 | from ifupdown2.ifupdown.utils import * | |
bd441a51 | 12 | except (ImportError, ModuleNotFoundError): |
d486dd0d JF |
13 | from ifupdown.utils import * |
14 | ||
14dc390d | 15 | |
16 | class templateEngine(): | |
904908bc | 17 | """ provides template rendering methods """ |
14dc390d | 18 | |
f27710fe RP |
19 | def __init__(self, template_engine, template_enable='0', |
20 | template_lookuppath=None): | |
14dc390d | 21 | self.logger = logging.getLogger('ifupdown.' + |
22 | self.__class__.__name__) | |
23 | self.tclass = None | |
24 | self.tclassargs = {} | |
25 | self.render = self._render_default | |
f27710fe RP |
26 | if template_enable == '0': |
27 | return | |
14dc390d | 28 | if template_engine == 'mako': |
29 | try: | |
30 | self.tclass = utils.importName('mako.template', 'Template') | |
3b01ed76 | 31 | except Exception as e: |
c46af1c9 | 32 | self.logger.warning('unable to load template engine %s (%s)' |
14dc390d | 33 | %(template_engine, str(e))) |
34 | pass | |
35 | if template_lookuppath: | |
36 | try: | |
37 | self.logger.debug('setting template lookuppath to %s' | |
38 | %template_lookuppath) | |
39 | lc = utils.importName('mako.lookup', 'TemplateLookup') | |
40 | self.tclassargs['lookup'] = lc( | |
41 | directories=template_lookuppath.split(':')) | |
3b01ed76 | 42 | except Exception as e: |
c46af1c9 | 43 | self.logger.warning('unable to set template lookup path' |
58329e8d JF |
44 | ' %s (%s): are you sure \'python-mako\'' |
45 | 'is installed?' | |
46 | % (template_lookuppath, str(e))) | |
14dc390d | 47 | self.render = self._render_mako |
48 | else: | |
49 | self.logger.info('skip template processing.., ' + | |
50 | 'template engine not found') | |
51 | ||
52 | def _render_default(self, textdata): | |
53 | return textdata | |
54 | ||
55 | def _render_mako(self, textdata): | |
56 | """ render textdata passed as argument using mako | |
57 | ||
58 | Returns rendered textdata """ | |
59 | ||
60 | if not self.tclass: | |
61 | return textdata | |
62 | self.logger.info('template processing on interfaces file ...') | |
63 | t = self.tclass(text=textdata, output_encoding='utf-8', | |
64 | lookup=self.tclassargs.get('lookup')) | |
65 | return t.render() |