def remote_gen_execute(self, arg, script_path, yield_stdout=False): """ run a single remote shell-script, raise ControlError on non-zero exit-code, optionally yields stdout line-per-line """ names = self.get_names() if isinstance(script_path, (list, tuple)): script_path = " ".join(script_path) rendered_path = str( CheetahTemplate(script_path, searchList=[self.get_names()])) remote = arg.node.get_remote(override=arg.method) lines = [] if yield_stdout else None color = colors.Output(sys.stdout, color=arg.color_mode).color exit_code = remote.execute(rendered_path, verbose=arg.verbose, output_lines=lines, quiet=arg.quiet, output_file=arg.output_file, color=color) if exit_code: raise errors.ControlError("%r failed with exit code %r" % (rendered_path, exit_code)) for line in (lines or []): yield line
def rendercheetah(obj, s=s): tvars = {'here':obj, 'container':obj.parentNode, 'config':obj.ownerDocument.config, 'context':obj.ownerDocument.context, 'templates':obj.renderer} return CheetahTemplate(source=s, searchList=[tvars], filter=CheetahUnicode).respond()
def render_cheetah(source_text, source_path, vars): assert CheetahTemplate, "Cheetah is not installed" try: return str( CheetahTemplate(source=source_text, file=source_path, searchList=[vars])) except (Cheetah.Template.Error, SyntaxError, Cheetah.NameMapper.NotFound) as error: raise errors.TemplateError("{0}: {1}: {2}".format( source_path, error.__class__.__name__, error))
def render_cheetah(self, source_path, dest_path): names = self.get_names() # TODO: template caching try: if source_path: source_path = str(CheetahTemplate(source_path, searchList=[names])) if source_path is not None: text = str(CheetahTemplate(file=source_path, searchList=[names])) else: text = None if dest_path: dest_path = str(CheetahTemplate(dest_path, searchList=[names])) return dest_path, text except (Cheetah.Template.Error, SyntaxError, Cheetah.NameMapper.NotFound), error: raise errors.VerifyError("%s: %s: %s" % ( source_path, error.__class__.__name__, error))
def render_genshi_xml(self, source_path, dest_path): assert genshi, "Genshi is not installed" names = self.get_names() if dest_path: dest_path = str(CheetahTemplate(dest_path, searchList=[names])) try: tmpl = genshi.template.MarkupTemplate(file(source_path), filepath=source_path) stream = tmpl.generate(**names) output = stream.render('xml') return dest_path, output except (errors.Error, genshi.template.TemplateError, IOError), error: raise errors.VerifyError(source_path, error)
def render(self, context): self.open() tpl = CheetahTemplate(self.xml['content'], namespaces=[context]) nc = unicode(tpl) # .encode('utf-8') if nc.startswith('<?xml version'): #~ nc = nc.replace('<?xml version="1.0" encoding="UTF-8"?>','') nc = nc.split('\n', 1)[1] self.xml['content'] = nc #~ odt = self.xhtml_to_odt(xhtml) #~ self.insert_content(odt) if True: f = open("content.xml", "wt") f.write(self.xml['content'].encode('utf-8')) f.close() self.add_styles() self.save(self.options.output)
def generate(self, tplname, fn, **context): from lino.api import rt from Cheetah.Template import Template as CheetahTemplate #~ if self.tmpl_dir: #~ tplname = join(self.tmpl_dir,tplname) #~ tplname = self.subcommand + '/' + tplname tpl_filename = rt.find_config_file(tplname, self.tmpl_dir) if tpl_filename is None: raise Exception("No file %s found" % tplname) if isinstance(tpl_filename, str): tpl_filename = tpl_filename.encode(sys.getfilesystemencoding()) tpl_filename = os.path.abspath(tpl_filename) fn = join(self.output_dir, fn) #~ if os.path.exists(fn): #~ if not self.options.get('overwrite'): #~ if not confirm("Overwrite existing file %s (y/n) ?" % fn): #~ logger.info("Skipping %s because file exists.",fn) #~ return #~ else: #~ mkdir_if(os.path.dirname(fn)) settings.SITE.makedirs_if_missing(os.path.dirname(fn)) logger.info("Generating %s", fn) #~ logger.info("Generating %s from %s",fn,tpl_filename) def app_labels(): return [p.app_label for p in settings.SITE.installed_plugins] context.update( lino=lino, #~ models=models, settings=settings, app_labels=app_labels) #~ d = dict(site=site) #~ print 20110223, [m for m in models.get_models()] #~ print 20110315, context tpl = CheetahTemplate(file=tpl_filename, namespaces=[context]) #~ tpl = CheetahTemplate(file(tpl_filename).read(),namespaces=[context]) s = str(tpl) #~ print s file(fn, 'w').write(s.encode('utf-8')) self.generated_count += 1
def TemplateFill(searchList, *path): template = templateRoot + ("/".join(path)) + ".tmplc" if (os.path.exists(template)): template = CheetahTemplate(file=template, searchList={ "object": searchList, "utils": { "simpleClassCreator": simpleClassCreator, "listClassCreator": listClassCreator, "pyClassCreator": pyClassCreator, "classId": classId } }) return str(template) else: return ""
def generate(self, tasks, plugin_api, callback): """ Fill template and run callback when finished. Created files are saved with the same suffix as the template. Opening the final file determines its type based on suffix. """ document = CheetahTemplate(file=self.get_path(), searchList=[{ 'tasks': tasks, 'plugin_api': plugin_api }]) suffix = ".%s" % self._get_suffix() output = tempfile.NamedTemporaryFile(suffix=suffix, delete=False) output.write(str(document)) self._document_path = output.name output.close() if self._script_path: self._run_script(callback) else: callback()
else: cheetah_template = CheetahTemplate("""\ #import cgi <!doctype html> <html> <head> <title>$cgi.escape($page_title)</title> </head> <body> <div class="header"> <h1>$cgi.escape($page_title)</h1> </div> <ul class="navigation"> #for $href, $caption in [('index.html', 'Index'), ('downloads.html', 'Downloads'), ('products.html', 'Products')]: <li><a href="$cgi.escape($href)">$cgi.escape($caption)</a></li> #end for </ul> <div class="table"> <table> #for $row in $table: <tr> #for $cell in $row: <td>$cell</td> #end for </tr> #end for </table> </div> </body> </html>\ """, searchList=[dict(context)])
import os from Cheetah.Template import Template as CheetahTemplate templateRoot = os.path.dirname( os.path.abspath(__file__)) + "/cheetahTemplates/" simpleClassCreator = CheetahTemplate( file=templateRoot + "/RuleBook/Rule/Handler/Include/Class.tmplc") listClassCreator = CheetahTemplate( file=templateRoot + "/RuleBook/Rule/Handler/Include/ListClass.tmplc") pyClassCreator = CheetahTemplate( file=templateRoot + "/RuleBook/Rule/Handler/Include/PyClass.tmplc") classId = CheetahTemplate(file=templateRoot + "/RuleBook/Rule/Handler/Include/ClassId.tmplc") simpleClassCreator.compile() def TemplateFill(searchList, *path): template = templateRoot + ("/".join(path)) + ".tmplc" if (os.path.exists(template)): template = CheetahTemplate(file=template, searchList={ "object": searchList, "utils": { "simpleClassCreator": simpleClassCreator, "listClassCreator": listClassCreator, "pyClassCreator": pyClassCreator, "classId": classId
def _render_cheetah(self, source=None, file=None): """helper to render a text or a file with Cheetah into a str""" names = self.get_names() return str( CheetahTemplate(source=source, file=file, searchList=[names]))
def render(self, context): t = CheetahTemplate(self.template, searchList=[context]) return str(t)