class MakoRenderFactory(object): def __init__(self, template_dirs, default_mime=None, **kw): # we'll handle the exception formatting, thanks. self.format_exceptions = kw.pop('format_exceptions', True) self.lookup = TemplateLookup(template_dirs, **kw) self.default_mime = default_mime or 'text/html' def __call__(self, template_filename): # trigger error if not found tmp_template = self.lookup.get_template(template_filename) for ext, mt in _EXT_MAP.items(): if template_filename.endswith(ext): mimetype = mt break else: mimetype = self.default_mime def mako_render(context): status = 200 template = self.lookup.get_template(template_filename) try: content = template.render_unicode(**context) except: if not self.format_exceptions: raise status = 500 if mimetype == 'text/html': content = exceptions.html_error_template().render() else: # TODO: add handling for other mimetypes? content = exceptions.text_error_template().render() return Response(content, status=status, mimetype=mimetype) return mako_render
def render_flatpage(request, f): """ Internal interface to the flat page view. """ # If registration is required for accessing this page, and the user isn't # logged in, redirect to the login page. if f.registration_required and not request.user.is_authenticated(): from django.contrib.auth.views import redirect_to_login return redirect_to_login(request.path) lookup = TemplateLookup(directories=[settings.TEMPLATES_DIR]) if f.template_name: #template = loader.select_template((f.template_name, DEFAULT_TEMPLATE)) template = lookup.get_template(f.template_name) else: #template = loader.get_template(DEFAULT_TEMPLATE) template = lookup.get_template(DEFAULT_TEMPLATE) # To avoid having to always use the "|safe" filter in flatpage templates, # mark the title and content as already safe (since they are raw HTML # content in the first place). f.title = mark_safe(f.title) f.content = mark_safe(f.content) #response = HttpResponse(template.render({'flatpage': f}, request)) rendered = template.render(flatpage=f) response = HttpResponse(rendered) return response
def get_node_manager_user_data(boto_data, uuid, max_request_size=10, chiles=True, jpeg2000=False, log_level='vvv'): here = dirname(__file__) user_data = join(here, '../user_data') mako_lookup = TemplateLookup(directories=[user_data]) template = mako_lookup.get_template('dfms_cloud_init.yaml') cloud_init = template.render( profile='aws-chiles02', aws_access_key_id=boto_data[0], aws_secret_access_key=boto_data[1], type='node manager', ) template = mako_lookup.get_template('node_manager_start_up.bash') user_script = template.render( uuid=uuid, queue=QUEUE, region=AWS_REGION, max_request_size=max_request_size, chiles=chiles, jpeg2000=jpeg2000, log_level=log_level ) user_data = get_user_data([cloud_init, user_script]) return user_data
def test_unicode_file_lookup(self): lookup = TemplateLookup(directories=[template_base], output_encoding="utf-8", default_filters=["decode.utf8"]) if compat.py3k: template = lookup.get_template("/chs_unicode_py3k.html") else: template = lookup.get_template("/chs_unicode.html") eq_(flatten_result(template.render_unicode(name="毛泽东")), u("毛泽东 是 新中国的主席<br/> Welcome 你 to 北京."))
def taskeditform(self, id=None, *args, **kwargs): if ormdb == "sqlite": # 為了避免跨執行緒使用 SQLite3, 重新 connect 資料庫 Database.connect() user = self.printuser() password, adsense, anonymous, mail_suffix, site_closed, read_only = self.parse_config(filename="pygroup_config") if read_only == "yes" and user != "admin": return "<a href='/'>Go to main page</a><br /><br />error, site is read only!" if user == "anonymous" and anonymous != "yes": raise cherrypy.HTTPRedirect("login") else: try: query = Task.at(int(id)).select() result = query.execute() data = result.one() output = "user:"******", owner:"+data.owner+"<br /><br />" if user != data.owner: if user != "admin": return output + "error! Not authorized!" else: template_lookup = TemplateLookup(directories=[template_root_dir+"/templates"]) mytemplate = template_lookup.get_template("taskeditform.html") return mytemplate.render(user=user, id=id, data=data) else: template_lookup = TemplateLookup(directories=[template_root_dir+"/templates"]) mytemplate = template_lookup.get_template("taskeditform.html") return mytemplate.render(user=user, id=id, data=data) except: return "error! Not authorized!"
def taskeditform(self, id=None, *args, **kwargs): user = self.printuser() password, adsense, anonymous, mail_suffix, site_closed, read_only = self.parse_config(filename="pygroup_config") if read_only == "yes" and user != "admin": return "<a href='/'>Go to main page</a><br /><br />error, site is read only!" if user == "anonymous" and anonymous != "yes": raise cherrypy.HTTPRedirect("login") else: try: db.connect() # 用 get() 取單筆資料 data = Task.select().where(Task.id==int(id)).get() output = "user:"******", owner:"+data.owner+"<br /><br />" if user != data.owner: if user != "admin": db.close() return output + "error! Not authorized!" else: template_lookup = TemplateLookup(directories=[template_root_dir+"/templates"]) mytemplate = template_lookup.get_template("taskeditform.html") db.close() return mytemplate.render(user=user, id=id, data=data) else: template_lookup = TemplateLookup(directories=[template_root_dir+"/templates"]) mytemplate = template_lookup.get_template("taskeditform.html") db.close() return mytemplate.render(user=user, id=id, data=data) except: db.close() return "error! Not authorized!"
class PyFFTest(PipeLineTest): """ Runs tests through the pyff cmdline - only mocks exit """ def setUp(self): super(PyFFTest, self).setUp() self.templates = TemplateLookup(directories=[os.path.join(self.datadir, 'simple-pipeline')]) self.output = tempfile.NamedTemporaryFile('w').name self.logfile = tempfile.NamedTemporaryFile('w').name self.signer = tempfile.NamedTemporaryFile('w').name self.signer_template = self.templates.get_template('signer.fd') with open(self.signer, "w") as fd: fd.write(self.signer_template.render(ctx=self)) self.bad = tempfile.NamedTemporaryFile('w').name self.bad_template = self.templates.get_template('bad.fd') with open(self.bad, "w") as fd: fd.write(self.bad_template.render(ctx=self)) def test_run_signer(self): out, err, exit_code = run_pyff("--loglevel=DEBUG", self.signer) assert err assert (exit_code == 0) def test_run_bad(self): out, err, exit_code = run_pyff("--loglevel=DEBUG", self.bad) assert 'Traceback' in err assert 'No pipe named snartibartifast is installed' in err assert (exit_code == 255) def test_run_signer_logfile(self): out, err, exit_code = run_pyff("--loglevel=DEBUG", "--logfile=%s" % self.logfile, self.signer) assert (exit_code == 0) def test_help(self): out, err, exit_code = run_pyff("--help") assert (pyffdoc in out) assert (exit_code == 0) def test_version(self): out, err, exit_code = run_pyff("--version") assert (pyffversion in out) assert (exit_code == 0) def test_bad_arg(self): out, err, exit_code = run_pyff("--snartibartfast") assert (exit_code == 2) assert ('snartibartfast' in out) def test_bad_loglevel(self): try: out, err, exit_code = run_pyff("--loglevel=TRACE") except ValueError as ex: assert ('TRACE' in str(ex)) def tear_down(self): super(PyFFTest, self).tearDown() os.unlink(self.signer) os.unlink(self.output) os.unlink(self.logfile)
def test_utf8_format_exceptions_pygments(self): """test that htmlentityreplace formatting is applied to exceptions reported with format_exceptions=True""" l = TemplateLookup(format_exceptions=True) if compat.py3k: l.put_string("foo.html", """# -*- coding: utf-8 -*-\n${'привет' + foobar}""") else: l.put_string("foo.html", """# -*- coding: utf-8 -*-\n${u'привет' + foobar}""") if compat.py3k: assert '<table class="error syntax-highlightedtable"><tr><td '\ 'class="linenos"><div class="linenodiv"><pre>2</pre>'\ '</div></td><td class="code"><div class="error '\ 'syntax-highlighted"><pre><span class="cp">${</span>'\ '<span class="s">'привет'</span> <span class="o">+</span> '\ '<span class="n">foobar</span><span class="cp">}</span>'\ '<span class="x"></span>' in \ result_lines(l.get_template("foo.html").render().decode('utf-8')) else: assert '<table class="error syntax-highlightedtable"><tr><td '\ 'class="linenos"><div class="linenodiv"><pre>2</pre>'\ '</div></td><td class="code"><div class="error '\ 'syntax-highlighted"><pre><span class="cp">${</span>'\ '<span class="s">u'прив'\ 'ет'</span> <span class="o">+</span> '\ '<span class="n">foobar</span><span class="cp">}</span>'\ '<span class="x"></span>' in \ result_lines(l.get_template("foo.html").render().decode('utf-8'))
class MakoTemplateLoader(Loader): def __init__(self, root_directory, app_name, **kwargs): super(MakoTemplateLoader, self).__init__(root_directory, **kwargs) path = os.path.abspath(root_directory) self._lookup = TemplateLookup(directories=path, input_encoding='utf-8', output_encoding='utf-8', encoding_errors='replace', filesystem_checks=settings.TEMPLATE_CONFIG.filesystem_checks, module_directory=os.path.abspath( os.path.join(settings.TEMPLATE_CONFIG.cache_directory, app_name)), default_filters=['decode.utf8'], collection_size=settings.TEMPLATE_CONFIG.collection_size, format_exceptions=settings.TEMPLATE_CONFIG.format_exceptions) def load(self, name): with self.lock: if os.path.isabs(name): path, file = os.path.split(name) self._lookup.directories = [path] template = self._lookup.get_template(file) else: template = self._lookup.get_template(name) template.generate = template.render return template def reset(self): pass
class MakoTemplateset(TemplatesetBase): '''Mako templateset (a wrapper to mako.lookup.TemplateLookup) Members: _lookup -- Mako lookup class ''' _lookup = None def __init__(self, *args, **kwargs): super(MakoTemplateset, self).__init__() self._lookup = ExternalMakoTemplateLookup(*args, **kwargs) # TemplateCollection interface def get_template(self, name): fname, defname = name.rsplit(':', 1) tpl = self._lookup.get_template(fname) tpl = tpl.get_def(defname) return MakoTemplate(tpl) get_template.__doc__ = TemplatesetBase.get_template.__doc__ def get_subset(self, name): return MakoTemplatesetFile(template_object=self._lookup.get_template(name))
def test_read_unicode(self): lookup = TemplateLookup(directories=[template_base], filesystem_checks=True, output_encoding='utf-8') if util.py3k: template = lookup.get_template('/read_unicode_py3k.html') else: template = lookup.get_template('/read_unicode.html') data = template.render(path=self._file_path('internationalization.html'))
class MakoTemplates(TemplateSystem): """Wrapper for Mako templates.""" name = "mako" lookup = None cache = {} def get_deps(self, filename): text = util.read_file(filename) lex = lexer.Lexer(text=text, filename=filename) lex.parse() deps = [] for n in lex.template.nodes: keyword = getattr(n, 'keyword', None) if keyword in ["inherit", "namespace"]: deps.append(n.attributes['file']) # TODO: include tags are not handled return deps def set_directories(self, directories, cache_folder): """Createa template lookup.""" cache_dir = os.path.join(cache_folder, '.mako.tmp') if os.path.exists(cache_dir): shutil.rmtree(cache_dir) self.lookup = TemplateLookup( directories=directories, module_directory=cache_dir, output_encoding='utf-8', ) def render_template(self, template_name, output_name, context): """Render the template into output_name using context.""" template = self.lookup.get_template(template_name) data = template.render_unicode(**context) if output_name is not None: try: os.makedirs(os.path.dirname(output_name)) except: pass with open(output_name, 'w+') as output: output.write(data) return data def template_deps(self, template_name): """Returns filenames which are dependencies for a template.""" # We can cache here because depedencies should # not change between runs if self.cache.get(template_name, None) is None: template = self.lookup.get_template(template_name) dep_filenames = self.get_deps(template.filename) deps = [template.filename] for fname in dep_filenames: deps += self.template_deps(fname) self.cache[template_name] = tuple(deps) return list(self.cache[template_name])
class PyFFTest(PipeLineTest): """ Runs tests through the pyff cmdline - only mocks exit """ def setUp(self): super(PyFFTest, self).setUp() self.templates = TemplateLookup(directories=[os.path.join(self.datadir, "simple-pipeline")]) self.output = tempfile.NamedTemporaryFile("w").name self.logfile = tempfile.NamedTemporaryFile("w").name self.signer = tempfile.NamedTemporaryFile("w").name self.signer_template = self.templates.get_template("signer.fd") with open(self.signer, "w") as fd: fd.write(self.signer_template.render(ctx=self)) self.bad = tempfile.NamedTemporaryFile("w").name self.bad_template = self.templates.get_template("bad.fd") with open(self.bad, "w") as fd: fd.write(self.bad_template.render(ctx=self)) def test_run_signer(self): out, err, exit_code = run_pyff("--loglevel=DEBUG", self.signer) assert not out assert err assert exit_code == 0 def test_run_bad(self): out, err, exit_code = run_pyff("--loglevel=DEBUG", self.bad) assert not out assert "Traceback" in err assert "No pipe named snartibartifast is installed" in err assert exit_code == 255 def test_run_signer_logfile(self): out, err, exit_code = run_pyff("--loglevel=DEBUG", "--logfile=%s" % self.logfile, self.signer) assert not out assert exit_code == 0 def test_help(self): out, err, exit_code = run_pyff("--help") assert pyffdoc in out assert exit_code == 0 def test_version(self): out, err, exit_code = run_pyff("--version") assert pyffversion in out assert exit_code == 0 def test_bad_arg(self): out, err, exit_code = run_pyff("--snartibartfast") assert exit_code == 2 assert "snartibartfast" in out def test_bad_loglevel(self): try: out, err, exit_code = run_pyff("--loglevel=TRACE") except ValueError, ex: assert "TRACE" in str(ex)
def test_callable(self): def get_modname(filename, uri): return os.path.join(module_base, os.path.dirname(uri)[1:], "foo", os.path.basename(filename) + ".py") lookup = TemplateLookup(template_base, modulename_callable=get_modname) t = lookup.get_template("/modtest.html") t2 = lookup.get_template("/subdir/modtest.html") eq_(t.module.__file__, os.path.join(module_base, "foo", "modtest.html.py")) eq_(t2.module.__file__, os.path.join(module_base, "subdir", "foo", "modtest.html.py"))
def test_callable(self): file('./test_htdocs/modtest.html', 'w').write("""this is a test""") file('./test_htdocs/subdir/modtest.html', 'w').write("""this is a test""") def get_modname(filename, uri): return os.path.dirname(filename) + "/foo/" + os.path.basename(filename) + ".py" lookup = TemplateLookup('./test_htdocs', modulename_callable=get_modname) t = lookup.get_template('/modtest.html') t2 = lookup.get_template('/subdir/modtest.html') assert t.module.__file__ == 'test_htdocs/foo/modtest.html.py' assert t2.module.__file__ == 'test_htdocs/subdir/foo/modtest.html.py'
def test_expression_declared(self): t = Template(""" ${",".join([t for t in ("a", "b", "c")])} """, strict_undefined=True) eq_(result_lines(t.render()), ['a,b,c']) t = Template(""" <%self:foo value="${[(val, n) for val, n in [(1, 2)]]}"/> <%def name="foo(value)"> ${value} </%def> """, strict_undefined=True) eq_(result_lines(t.render()), ['[(1, 2)]']) t = Template(""" <%call expr="foo(value=[(val, n) for val, n in [(1, 2)]])" /> <%def name="foo(value)"> ${value} </%def> """, strict_undefined=True) eq_(result_lines(t.render()), ['[(1, 2)]']) l = TemplateLookup(strict_undefined=True) l.put_string("i", "hi, ${pageargs['y']}") l.put_string("t", """ <%include file="i" args="y=[x for x in range(3)]" /> """) eq_( result_lines(l.get_template("t").render()), ['hi, [0, 1, 2]'] ) l.put_string('q', """ <%namespace name="i" file="${(str([x for x in range(3)][2]) + 'i')[-1]}" /> ${i.body(y='x')} """) eq_( result_lines(l.get_template("q").render()), ['hi, x'] ) t = Template(""" <% y = lambda q: str(q) %> ${y('hi')} """, strict_undefined=True) eq_( result_lines(t.render()), ["hi"] )
def test_read_unicode(self): lookup = TemplateLookup(directories=[template_base], filesystem_checks=True, output_encoding="utf-8") if compat.py3k: template = lookup.get_template("/read_unicode_py3k.html") else: template = lookup.get_template("/read_unicode.html") # TODO: I've no idea what encoding this file is, Python 3.1.2 # won't read the file even with open(...encoding='utf-8') unless # errors is specified. or if there's some quirk in 3.1.2 # since I'm pretty sure this test worked with py3k when I wrote it. data = template.render(path=self._file_path("internationalization.html"))
def test_custom_writer(self): canary = [] def write_module(source, outputpath): f = open(outputpath, "wb") canary.append(outputpath) f.write(source) f.close() lookup = TemplateLookup(template_base, module_writer=write_module, module_directory=module_base) t = lookup.get_template("/modtest.html") t2 = lookup.get_template("/subdir/modtest.html") eq_(canary, [os.path.join(module_base, "modtest.html.py"), os.path.join(module_base, "subdir/modtest.html.py")])
def test_unicode_file_lookup(self): lookup = TemplateLookup( directories=[template_base], output_encoding='utf-8', default_filters=['decode.utf8']) if compat.py3k: template = lookup.get_template('/chs_unicode_py3k.html') else: template = lookup.get_template('/chs_unicode.html') eq_( flatten_result(template.render_unicode(name='毛泽东')), u('毛泽东 是 新中国的主席<br/> Welcome 你 to 北京.') )
def MakeModule(config, module): """ Generates the output html from templates. """ mylookup = TemplateLookup(directories=[config['templates'], config['modules']], input_encoding='utf-8', output_encoding='utf-8', encoding_errors='replace' ) top = mylookup.get_template(config['top']).render() bottom = mylookup.get_template(config['bottom']).render() set = mylookup.get_template(module).render() return ''.join([top, set, bottom])
def run(taskList): scriptDir = os.path.dirname(os.path.realpath(__file__)) mylookup = TemplateLookup( directories=[scriptDir], imports=['from generator.rcg import list, getMethodParamListN, getParamFlags, getParamTypeId'] ) templates = { 'library': TemplateSet(mylookup, 'library'), 'object': TemplateSet(mylookup, 'object'), 'scene': TemplateSet(mylookup, 'object'), 'component': TemplateSet(mylookup, 'object'), 'actor': TemplateSet(mylookup, 'object'), 'entity': TemplateSet(mylookup, 'object'), } with open('temp/globals.cdef', 'r') as globalsFile: globalsContent = globalsFile.read() globalsJson = json.loads(globalsContent) for t in taskList: cdefPath = t['cdef'] with open(cdefPath, 'r') as cdefFile: cdefContent = cdefFile.read() cdefList = json.loads(cdefContent) if cdefList == None: continue for c in cdefList: cName = c['name'] cType = c['type'] cTemplate = c['template'] c['globals'] = globalsJson if t['regenerate'] == True: pathFmt = 'temp/generated/{0}.generated.{1}' templSet = templates[cTemplate] generate(c, templSet.declaration, pathFmt.format(cName, 'hpp')) generate(c, templSet.inline, pathFmt.format(cName, 'inl')) generate(c, templSet.definition, pathFmt.format(cName, 'cpp')) # If task list was empty, then nothing has changed and no need to regenerate register.cpp if len(taskList) > 0: template = mylookup.get_template('game.generated.cpp') generate({'globals': globalsJson}, template, 'game.generated.cpp') template = mylookup.get_template('game.generated.hpp') generate({'globals': globalsJson}, template, 'game.generated.hpp')
def get_template(template_name): if template_name.endswith('.css'): global _css_template_lookup if not _css_template_lookup: _css_template_lookup = TemplateLookup(directories=[_template_dir], default_filters=['unicode']) return _css_template_lookup.get_template(template_name) else: global _template_lookup if not _template_lookup: _template_lookup = TemplateLookup( directories=[_template_dir], default_filters=['escape_silent'], imports=['from markupsafe import escape_silent']) return _template_lookup.get_template(template_name)
def test_bytestring_passthru(self): lookup = TemplateLookup(directories=['./test_htdocs'], default_filters=[], disable_unicode=True) template = lookup.get_template('/chs_utf8.html') self.assertEquals(flatten_result(template.render(name='毛泽东')), '毛泽东 是 新中国的主席<br/> Welcome 你 to 北京. Welcome 你 to 北京.') lookup = TemplateLookup(directories=['./test_htdocs'], disable_unicode=True) template = lookup.get_template('/chs_utf8.html') self.assertEquals(flatten_result(template.render(name='毛泽东')), '毛泽东 是 新中国的主席<br/> Welcome 你 to 北京. Welcome 你 to 北京.') self.assertRaises(UnicodeDecodeError, template.render_unicode, name='毛泽东') template = Template("""${'Alors vous imaginez ma surprise, au lever du jour, quand une drôle de petit voix m’a réveillé. Elle disait: « S’il vous plaît… dessine-moi un mouton! »'}""", disable_unicode=True, input_encoding='utf-8') assert template.render() == """Alors vous imaginez ma surprise, au lever du jour, quand une drôle de petit voix m’a réveillé. Elle disait: « S’il vous plaît… dessine-moi un mouton! »""" template = Template("""${'Alors vous imaginez ma surprise, au lever du jour, quand une drôle de petit voix m’a réveillé. Elle disait: « S’il vous plaît… dessine-moi un mouton! »'}""", input_encoding='utf8', output_encoding='utf8', disable_unicode=False, default_filters=[]) self.assertRaises(UnicodeDecodeError, template.render) # raises because expression contains an encoded bytestring which cannot be decoded
def gen_docs(root, sections, html=True): """Generates documentation for sciSQL, either in HTML or as a set of MySQL tables (for the LSST schema browser). """ lookup = TemplateLookup(directories=[os.path.join(root, 'tools', 'templates')]) if html: template = lookup.get_template('index.mako') with open(os.path.join(root, 'doc', 'index.html'), 'w') as f: f.write(template.render(sections=sections, SCISQL_VERSION=os.environ['SCISQL_VERSION'])) else: template = lookup.get_template('lsst_schema_browser.mako') with open('metadata_scisql.sql', 'w') as f: f.write(template.render(sections=sections, SCISQL_VERSION=os.environ['SCISQL_VERSION']))
def get_template(self, uri): """Fetch a template from the cache, or check the filesystem for it In addition to the basic filesystem lookup, this subclass will use pkg_resource to load a file using the asset specification syntax. """ isabs = os.path.isabs(uri) if (not isabs) and (':' in uri): # Windows can't cope with colons in filenames, so we replace the # colon with a dollar sign in the filename mako uses to actually # store the generated python code in the mako module_directory or # in the temporary location of mako's modules adjusted = uri.replace(':', '$') try: if self.filesystem_checks: return self._check(adjusted, self._collection[adjusted]) else: return self._collection[adjusted] except KeyError: pname, path = resolve_asset_spec(uri) srcfile = abspath_from_asset_spec(path, pname) if os.path.isfile(srcfile): return self._load(srcfile, adjusted) raise exceptions.TopLevelLookupException( "Can not locate template for uri %r" % uri) return TemplateLookup.get_template(self, uri)
class MakoBridge(TemplateBridge): def init(self, builder, *args, **kw): self.layout = builder.config.html_context.get('mako_layout', 'html') builder.config.html_context['release_date'] = builder.config['release_date'] builder.config.html_context['versions'] = builder.config['versions'] self.lookup = TemplateLookup(directories=builder.config.templates_path, #format_exceptions=True, imports=[ "from builder import util" ] ) def render(self, template, context): template = template.replace(".html", ".mako") context['prevtopic'] = context.pop('prev', None) context['nexttopic'] = context.pop('next', None) context['mako_layout'] = self.layout == 'html' and 'static_base.mako' or 'site_base.mako' # sphinx 1.0b2 doesn't seem to be providing _ for some reason... context.setdefault('_', lambda x:x) return self.lookup.get_template(template).render_unicode(**context) def render_string(self, template, context): context['prevtopic'] = context.pop('prev', None) context['nexttopic'] = context.pop('next', None) context['mako_layout'] = self.layout == 'html' and 'static_base.mako' or 'site_base.mako' # sphinx 1.0b2 doesn't seem to be providing _ for some reason... context.setdefault('_', lambda x:x) return Template(template, lookup=self.lookup, format_exceptions=True, imports=[ "from builder import util" ] ).render_unicode(**context)
def taskform(self, id=0, *args, **kwargs): user = self.printuser() template_lookup = TemplateLookup(directories=[template_root_dir+"/templates"]) # 必須要從 templates 目錄取出 tasklist.html # 針對 id != 0 時, 表示要回應主資料緒, 希望取出與 id 對應的資料標頭, 然後加上 Re: mytemplate = template_lookup.get_template("taskform.html") return mytemplate.render(user=user, id=id)
class TemplateEngine: def __init__(self, config: dict): """ Constructor :param config: dict with keys: 'TEMPLATE_DIR' - directory where to read template html files from 'TEMPLATE_CACHE_DIR' - dir to store compiled templates in :return: None """ if 'TEMPLATE_DIR' not in config: config['TEMPLATE_DIR'] = '.' if 'TEMPLATE_CACHE_DIR' not in config: config['TEMPLATE_CACHE_DIR'] = '.' params = { 'directories': config['TEMPLATE_DIR'], 'module_directory': config['TEMPLATE_CACHE_DIR'], # 'input_encoding': 'utf-8', # 'output_encoding': 'utf-8', # 'encoding_errors': 'replace', 'strict_undefined': True } self._lookup = TemplateLookup(**params) self._args = dict() def assign(self, vname, vvalue): """ Assign template variable value :param vname: - variable name :param vvalue: - variable value :return: None """ self._args[vname] = vvalue def unassign(self, vname): """ Unset template variablr :param vname: - variable name :return: None """ if vname in self._args: self._args.pop(vname) def render(self, tname: str, expose_errors=True) -> str: """ Renders specified template file and returns result as string, ready to be sent to browser. :param tname: - template file name :param expose_errors: - if true, any exception will be returned in result string :return: rendered template text """ ret = '' try: tmpl = self._lookup.get_template(tname) ret = tmpl.render(**self._args) except exceptions.MakoException: if expose_errors: ret = exceptions.html_error_template().render() else: ret = 'Error rendering template: [' + tname + ']' return ret
def test_includes(self): lookup = TemplateLookup() lookup.put_string("incl1.tmpl", """ <%page args="bar" /> ${bar} ${pageargs['foo']} """ ) lookup.put_string("incl2.tmpl", """ ${pageargs} """ ) lookup.put_string("index.tmpl", """ <%include file="incl1.tmpl" args="**pageargs"/> <%page args="variable" /> ${variable} <%include file="incl2.tmpl" /> """) self._do_test( lookup.get_template("index.tmpl"), "bar foo var {}", filters=flatten_result, template_args={'variable':'var', 'bar':'bar', 'foo':'foo'} )
class MakoBridge(TemplateBridge): def init(self, builder, *args, **kw): self.layout = builder.config.html_context.get('mako_layout', 'html') directories = [os.path.join(os.path.dirname(__file__), '..', t) for t in builder.config.templates_path ] self.lookup = TemplateLookup(directories=directories, format_exceptions=True, imports=[ "from builder import util" ] ) def render(self, template, context): template = template.replace(".html", ".mako") context['prevtopic'] = context.pop('prev', None) context['nexttopic'] = context.pop('next', None) context['mako_layout'] = self.layout == 'html' and 'static_base.mako' or 'site_base.mako' return self.lookup.get_template(template).render_unicode(**context) def render_string(self, template, context): context['prevtopic'] = context.pop('prev', None) context['nexttopic'] = context.pop('next', None) context['mako_layout'] = self.layout == 'html' and 'static_base.mako' or 'site_base.mako' return Template(template, lookup=self.lookup, format_exceptions=True, imports=[ "from builder import util" ] ).render_unicode(**context)
class MakoBridge(TemplateBridge): def init(self, builder, *args, **kw): self.jinja2_fallback = BuiltinTemplateLoader() self.jinja2_fallback.init(builder, *args, **kw) builder.config.html_context['site_base'] = builder.config['site_base'] self.lookup = TemplateLookup( directories=builder.config.templates_path, imports=["from builder import util"], #format_exceptions=True, ) def render(self, template, context): template = template.replace(".html", ".mako") context['prevtopic'] = context.pop('prev', None) context['nexttopic'] = context.pop('next', None) # RTD layout if rtd: # add variables if not present, such # as if local test of READTHEDOCS variable if 'MEDIA_URL' not in context: context['MEDIA_URL'] = "http://media.readthedocs.org/" if 'slug' not in context: context['slug'] = "mako-test-slug" if 'url' not in context: context['url'] = "/some/test/url" if 'current_version' not in context: context['current_version'] = "some_version" if 'versions' not in context: context['versions'] = [('default', '/default/')] context['docs_base'] = "http://readthedocs.org" context['toolbar'] = True context['layout'] = "rtd_layout.mako" context['pdf_url'] = "%spdf/%s/%s/%s.pdf" % ( context['MEDIA_URL'], context['slug'], context['current_version'], context['slug']) # local docs layout else: context['toolbar'] = False context['docs_base'] = "/" context['layout'] = "layout.mako" context.setdefault('_', lambda x: x) return self.lookup.get_template(template).render_unicode(**context) def render_string(self, template, context): # this is used for .js, .css etc. and we don't have # local copies of that stuff here so use the jinja render. return self.jinja2_fallback.render_string(template, context)
class OCGenerator: def __init__(self, model, outPath, type=OCOutType.BWModel, template=None): self.model = model self.outPath = outPath appPath = os.path.split(os.path.realpath(__file__))[0] if template == None: if type == OCOutType.Dic: templatePath = appPath + "/../../resources/template/oc/dic" elif type == OCOutType.Mantle: templatePath = appPath + "/../../resources/template/oc/mantle" elif type == OCOutType.BWModel: templatePath = appPath + "/../../resources/template/oc/bwmodel" else: sys.exit("OC不支持该输出选项") else: templatePath = template print(templatePath) self.type = type self.tlLookup = TemplateLookup(directories=templatePath) def renderFileContent(self, file): fileTl = self.tlLookup.get_template(file) content = fileTl.render(model=self.model) return content def outputFileWithRender(self, filename, tlname): filePath = os.path.join(self.outPath, filename) content = self.renderFileContent(tlname) f = codecs.open(filePath, "w+", "utf-8") f.write(content) f.close() def outputFilename(self): return self.model.name def output(self): if os.path.exists(self.outPath) == False: os.mkdir(self.outPath) headerFile = self.outputFilename() + ".h" implatationFile = self.outputFilename() + ".m" self.outputFileWithRender(headerFile, "model_header.clout") self.outputFileWithRender(implatationFile, "model_implatation.clout") if self.type == OCOutType.Dic: self.outputFileWithRender("EnsureType.h", "EnsureType.h") self.outputFileWithRender("EnsureType.m", "EnsureType.m") self.outputFileWithRender("BWModelProtocol.h", "BWModelProtocol.h") self.outputFileWithRender("BWTODictionary.h", "BWTODictionary.h") self.outputFileWithRender("BWTODictionary.m", "BWTODictionary.m") self.outputFileWithRender("BWDeepCopy.h", "BWDeepCopy.h") self.outputFileWithRender("BWDeepCopy.m", "BWDeepCopy.m")
class MakoTemplates(BaseEngine): app_dirname = settings.MAKO_DIR_NAME def __init__(self, params): params = params.copy() options = params.pop("OPTIONS").copy() super(MakoTemplates, self).__init__(params) # Defaut values for initializing the MakoTemplateLookup class # You can define them in the backend OPTIONS dict. options.setdefault("directories", self.template_dirs) options.setdefault("module_directory", tempfile.gettempdir()) options.setdefault("input_encoding", "utf-8") options.setdefault("output_encoding", "utf-8") options.setdefault("encoding_errors", "replace") options.setdefault("collection_size", 500) options.setdefault( "default_filters", settings.MAKO_DEFAULT_FILTERS if hasattr(settings, "MAKO_DEFAULT_FILTERS") else [], ) # Use context processors like Django context_processors = options.pop("context_processors", []) self.context_processors = context_processors # Use the mako template lookup class to find templates self.lookup = MakoTemplateLookup(**options) @cached_property def template_context_processors(self): context_processors = _builtin_context_processors context_processors += tuple(self.context_processors) return tuple(import_string(path) for path in set(context_processors)) def from_string(self, template_code): try: return Template(MakoTemplate(template_code, lookup=self.lookup), []) except mako_exceptions.SyntaxException as err: raise TemplateSyntaxError(err.args) def get_template(self, template_name): try: return Template( self.lookup.get_template(template_name), self.template_context_processors, ) except mako_exceptions.TemplateLookupException as err: raise TemplateDoesNotExist(err.args) except mako_exceptions.CompileException as err: raise TemplateSyntaxError(err.args)
def render(self, renderJobs=None): """ Does the render. It goes threw the renderJobs and renders all. """ if renderJobs is not None: self.renderJobs = renderJobs for k, job in self.renderJobs['jobs'].items(): try: # # Render the file. Note, that the output of folowing codes is # syntatically/semantically correct but hard to read. So post process needed. # logging.info(" Start rendering jobs, named: '%s' ...", k) # fetch render template mylookup = TemplateLookup(directories=[resourcepath]) mytemplate = mylookup.get_template(job['templateFile']) # DO the RENDER generated_code = mytemplate.render( lic=MIT_LICENSE, commondata = self.renderJobs['common'], renderdata = job['renderdata'] ) # # Beautifier # Make more readable the output file. # logging.info(" Start beautifier ...") # Fetch beautifier parameters: indentUnit=self.renderJobs['common']['indentUnit'] beautifierFunc = job['beautifierFunc'] method_to_call = getattr(sys.modules[__name__], beautifierFunc) # BEAUTIFY: generated_code = method_to_call(generated_code, indentUnit=indentUnit) # save file: outdir=self.db['configuration']['hdl']['rtlPath'] os.makedirs(outdir, exist_ok=True) filename = job['outFilename'] outfile = os.path.abspath(os.path.join(outdir, filename)) logging.info(" Saving file to %s ...", outfile) with open(outfile, 'w', newline='\n') as f: f.write('\n'.join(generated_code)) except: traceback = RichTraceback() for (filename, lineno, function, line) in traceback.traceback: print("File %s, line %s, in %s" % (filename, lineno, function)) print(line, "\n") print("%s: %s" % (str(traceback.error.__class__.__name__), traceback.error))
def send(self, job, message, config=None): """ Sends mail using configured mail settings. If `attachments` is true, a list compromised of the following dict is required via HTTP upload: - headers(list) - name(str) - value(str) - params(dict) - content (str) [ { "headers": [ { "name": "Content-Transfer-Encoding", "value": "base64" }, { "name": "Content-Type", "value": "application/octet-stream", "params": { "name": "test.txt" } } ], "content": "dGVzdAo=" } ] """ gc = self.middleware.call_sync('datastore.config', 'network.globalconfiguration') hostname = f'{gc["gc_hostname"]}.{gc["gc_domain"]}' message['subject'] = f'{hostname}: {message["subject"]}' if 'html' not in message: lookup = TemplateLookup(directories=[ os.path.join(os.path.dirname(os.path.realpath(__file__)), '../assets/templates') ], module_directory="/tmp/mako/templates") tmpl = lookup.get_template('mail.html') message['html'] = tmpl.render( body=markdown2.markdown(message['text'])) return self.send_raw(job, message, config)
def main(args): cache = None if cache: cache = os.path.join(context.cache_dir, 'mako') lookup = TemplateLookup( directories=[os.path.join(pwnlib.data.path, 'templates')], module_directory=cache) # For the SSH scenario, check that the binary is at the # same path on the remote host. if args.user: if not (args.path or args.exe): log.error("Must specify --path or a exe") s = ssh(args.user, args.host, args.port or 22, args.password or None) try: remote = args.path or args.exe s.download(remote) except Exception: log.warning("Could not download file %r, opening a shell", remote) s.interactive() return if not args.exe: args.exe = os.path.basename(args.path) template = lookup.get_template('pwnup.mako') output = template.render(args.exe, args.host, args.port, args.user, args.password, args.path, args.quiet) # Fix Mako formatting bs output = re.sub('\n\n\n', '\n\n', output) # Colorize the output if it's a TTY if args.color == 'always' or (args.color == 'auto' and sys.stdout.isatty()): from pygments import highlight from pygments.formatters import TerminalFormatter from pygments.lexers.python import PythonLexer output = highlight(output, PythonLexer(), TerminalFormatter()) print(output) # If redirected to a file, make the resulting script executable if not sys.stdout.isatty(): try: os.fchmod(sys.stdout.fileno(), 0o700) except OSError: pass
def __call__(self, value, system): """ Returns the XML encoded extract, according to the specification. Args: value (tuple): A tuple containing the generated extract record and the params dictionary. system (dict): The available system properties. Returns: str: The XML encoded extract. """ self._request = self.get_request(system) response = self.get_response(system) if isinstance( response, Response ) and response.content_type == response.default_content_type: response.content_type = 'application/xml' self._params_ = value[1] if not isinstance(self._params_, Parameter): raise TypeError( 'Missing parameter definition; Expected {0}, got {1} instead'. format(Parameter, self._params_.__class__)) if self._params_.language: self._language = str(self._params_.language).lower() templates = TemplateLookup(directories=[self.template_dir], output_encoding='utf-8', input_encoding='utf-8') template = templates.get_template('extract.xml') try: content = template.render( **{ 'extract': value[0], 'params': value[1], 'sort_by_localized_text': self.sort_by_localized_text, 'localized': self.get_localized_text, 'multilingual': self.get_multilingual_text, 'request': self._request, 'get_symbol_ref': self.get_symbol_ref, 'get_gml_id': self._get_gml_id, 'get_document_type': self._get_document_type, 'date_format': '%Y-%m-%dT%H:%M:%S' }) return content except ValueError as e: # TODO: use error mapping to provide HTTP errors raise e except Exception: response.content_type = 'text/html' return exceptions.html_error_template().render()
class SaltMakoTemplateLookup(TemplateCollection): """ Look up Mako template files on Salt master via salt://... URLs. If URL is a relative path(without an URL scheme) then assume it's relative to the directory of the salt file that's doing the lookup(with <%include/> or <%namespace/>). If URL is an absolute path then it's treated as if it has been prefixed with salt://. Examples:: <%include file="templates/sls-parts.mako"/> <%namespace file="salt://lib/templates/utils.mako" import="helper"/> """ def __init__(self, opts, env='base'): self.opts = opts self.env = env if opts['file_client'] == 'local': searchpath = opts['file_roots'][env] else: searchpath = [os.path.join(opts['cachedir'], 'files', env)] self.lookup = TemplateLookup(directories=searchpath) self.file_client = salt.fileclient.get_file_client(self.opts) self.cache = {} def adjust_uri(self, uri, filename): scheme = urlparse.urlparse(uri).scheme if scheme == 'salt': return uri elif scheme: raise ValueError("Unsupported URL scheme(%s) in %s" % \ (scheme, uri)) else: return self.lookup.adjust_uri(uri, filename) def get_template(self, uri): prefix = "salt://" salt_uri = uri if uri.startswith(prefix) else prefix+uri self.cache_file(salt_uri) return self.lookup.get_template(salt_uri[len(prefix):]) def cache_file(self, fpath): if fpath not in self.cache: self.cache[fpath] = \ self.file_client.get_file(fpath, '', True, self.env)
def generate_morphline_config(self, collection_name, data, uuid_name=None): """ Input: data: { 'type': {'name': 'My New Collection!' format': 'csv', 'columns': [{'name': business_id, 'included': True', 'type': 'string'}, cool, date], fieldSeparator : ",", recordSeparator: '\n', quoteChar : "\""}, 'transformation': [ 'country_code': {'replace': {'FRA': 'FR, 'CAN': 'CA'..}} 'ip': {'geoIP': } ] } Output: Morphline content 'SOLR_LOCATOR : { ...}' """ geolite_loc = os.path.join(CONFIG_INDEXER_LIBS_PATH.get(), "GeoLite2-City.mmdb") grok_dicts_loc = os.path.join(CONFIG_INDEXER_LIBS_PATH.get(), "grok_dictionaries") properties = { "collection_name": collection_name, "fields": self.get_field_list(data['columns']), "num_base_fields": len(data['columns']), "uuid_name": uuid_name, "get_regex": Indexer._get_regex_for_type, "format_settings": data['format'], "format_class": get_file_format_class(data['format']['type']), "get_kept_args": get_checked_args, "grok_dictionaries_location": grok_dicts_loc if self.fs and self.fs.exists(grok_dicts_loc) else None, "geolite_db_location": geolite_loc if self.fs and self.fs.exists(geolite_loc) else None, "zk_host": zkensemble() } oozie_workspace = CONFIG_INDEXING_TEMPLATES_PATH.get() lookup = TemplateLookup(directories=[oozie_workspace]) morphline = lookup.get_template("morphline_template.conf").render( **properties) return morphline
def generate_config_file(__template_name__, __config_file_path__, **kwargs): """Generate a bundle config file from a template, supplying arguments from kwargs.""" # Load the template lookup = TemplateLookup(directories=[WORKER_TEMPLATE_DIR]) template = lookup.get_template(__template_name__) # Instantiate the template instance = template.render(**kwargs) # Write the instantiated template to the bundle f = open(__config_file_path__, 'w') f.write(instance) f.close()
def test_builtin_names_dont_clobber_defaults_in_includes(self): lookup = TemplateLookup() lookup.put_string( "test.mako", """ <%include file="test1.mako"/> """) lookup.put_string( "test1.mako", """ <%page args="id='foo'"/> ${id} """) for template in ("test.mako", "test1.mako"): assert flatten_result( lookup.get_template(template).render()) == "foo" assert flatten_result( lookup.get_template(template).render(id=5)) == "5" assert flatten_result(lookup.get_template(template).render( id=id)) == "<built-in function id>"
class DemoSystem(object): def __init__(self): self.lookup = TemplateLookup(directories=[path(__file__).dirname() / 'templates']) self.DEBUG = True def render_template(self, template_filename, dictionary, context=None): if context is None: context = {} context_dict = {} context_dict.update(dictionary) context_dict.update(context) return self.lookup.get_template(template_filename).render(**context_dict)
def index(self): """ simple demo index page """ tmpl_dir = os.path.join(os.path.dirname(__file__), 'lib', 'template') tmpl_lookup = TemplateLookup(directories=[tmpl_dir], input_encoding='utf-8', output_encoding='utf-8', encoding_errors='replace') return tmpl_lookup.get_template('index.html')\ .render(indexd=self.indexd, title="Demonstrations", description="")
def render_template(filename, **ns): """Renders a template giving a filename and a keyword dictionary @filename: a template filename to render @kwargs: keyword arguments to send to the template @return: the rendered template """ directories = environ.get_resource_filename('stoq', 'template') lookup = TemplateLookup(directories=directories, output_encoding='utf8', input_encoding='utf8', default_filters=['h']) tmpl = lookup.get_template(filename) return tmpl.render(**ns)
def mako_mq(dirname, verbose=False): DEFAULT_DIR = os.path.join(BASEPATH, 'mako') from mako.template import Template from mako.lookup import TemplateLookup lookup = TemplateLookup(directories=[DEFAULT_DIR], filesystem_checks=False) template = lookup.get_template('subs_mq.html') def render(): return template.render(**DATA.copy()) if verbose: pr(template.code, render()) return render
def do(): # Split the path into template name and directory name = os.path.basename(path) dir = os.path.dirname(path) # This will be where we search for templates lookup = TemplateLookup(directories=[dir], module_directory="/tmp/mako/%s" % dir) # Get the template by its relative path tmpl = lookup.get_template(name) # Render the template return tmpl.render(middleware=self.service.middleware)
def test_callable(self): def get_modname(filename, uri): return os.path.join( config.module_base, os.path.dirname(uri)[1:], "foo", os.path.basename(filename) + ".py", ) lookup = TemplateLookup(config.template_base, modulename_callable=get_modname) t = lookup.get_template("/modtest.html") t2 = lookup.get_template("/subdir/modtest.html") eq_( t.module.__file__, os.path.join(config.module_base, "foo", "modtest.html.py"), ) eq_( t2.module.__file__, os.path.join(config.module_base, "subdir", "foo", "modtest.html.py"), )
class View_cl(object): #---------------------------------------------------------- #------------------------------------------------------- def __init__(self): #------------------------------------------------------- self.lookup_o = TemplateLookup('./templates') #------------------------------------------------------- def createList_px(self, data_opl, listform): # listform #------------------------------------------------------- if (listform == 'tabelle'): template_o = self.lookup_o.get_template('list.tpl') listformNow = "tabelle" listformNew = "liste" #Für die umschalter listformNewText = "Liste" elif (listform == 'liste'): template_o = self.lookup_o.get_template('list2.tpl') listformNow = "liste" listformNew = "tabelle" listformNewText = "Tabelle" markup_s = template_o.render(data_o = data_opl, listformNow = listformNow, listformNew = listformNew, listformNewText = listformNewText) return markup_s #------------------------------------------------------- def createForm_px(self, listformNow, id_spl, data_opl): #------------------------------------------------------- template_o = self.lookup_o.get_template('form.tpl') markup_s = template_o.render(listformNow = listformNow, data_o = data_opl, key_s = id_spl) return markup_s #------------------------------------------------------- def readFile_p(self, fileName_spl): #------------------------------------------------------- content_s = '' with codecs.open(os.path.join('templates', fileName_spl), 'r', 'utf-8') as fp_o: content_s = fp_o.read() return content_s
def serve_template(templatename, **kwargs): interface_dir = os.path.join(str(lazylibrarian.PROG_DIR), 'data/interfaces/') template_dir = os.path.join(str(interface_dir), lazylibrarian.HTTP_LOOK) _hplookup = TemplateLookup(directories=[template_dir]) try: template = _hplookup.get_template(templatename) return template.render(**kwargs) except: return exceptions.html_error_template().render()
def serve_template(name, **kwargs): try: loc = os.path.join(htpc.RUNDIR, 'interfaces/', htpc.settings.get('app_template', 'default')) template = TemplateLookup(directories=[os.path.join(loc, 'html/')]) return template.get_template(name).render(**kwargs) except Exception as e: logger.error('%s' % exceptions.text_error_template()) if htpc.DEV or htpc.LOGLEVEL == 'debug': return exceptions.html_error_template().render()
def renderTemplate(attrib, template): try: tmp_lookup = TemplateLookup(attrib['tmp_dir']) tmp = tmp_lookup.get_template(template) file_dir = os.path.join(attrib['tmp_write_dir'], attrib['filename']) with open(file_dir, 'w', newline='') as fTmp: fTmp.write(tmp.render(data=attrib)) except Exception as e: print(e)
def process_report(self, r): lookup = TemplateLookup(directories=[self.template_dir]) template = lookup.get_template("report.html") self.output("Rendering template") output = template.render(report=r).encode("utf-8") output_filename = os.path.join(self.out_dir, r["title"], "%s.html" % r["title"]) self.output("Writing file to %s" % os.path.dirname(output_filename)) os.makedirs(os.path.dirname(output_filename)) with open(output_filename, "w") as f: f.write(output)
def prepare(self, **options): from mako.template import Template from mako.lookup import TemplateLookup options.update({'input_encoding': self.encoding}) #TODO: This is a hack... https://github.com/defnull/mole/issues#issue/8 mylookup = TemplateLookup(directories=['.'] + self.lookup, **options) if self.source: self.tpl = Template(self.source, lookup=mylookup) else: #mako cannot guess extentions. We can, but only at top level... name = self.name if not os.path.splitext(name)[1]: name += os.path.splitext(self.filename)[1] self.tpl = mylookup.get_template(name)
def mako(dirname, verbose=False): from mako.template import Template from mako.lookup import TemplateLookup lookup = TemplateLookup(directories=[dirname], filesystem_checks=False) template = lookup.get_template("template.html") def render(): return template.render(title=TITLE, user=USER, list_items=ITEMS) if verbose: print(template.code + " " + render()) return render
def test_user_specified_service(self): """ When a service name is specified by the user The mako integration should use it as the service name """ tmpl_lookup = TemplateLookup(directories=[TMPL_DIR]) t = tmpl_lookup.get_template('template.html') self.assertEqual(t.render(name='mako'), 'Hello mako!\n') spans = self.tracer.writer.pop() self.assertEqual(len(spans), 1) assert spans[0].service == "mysvc"
def _process_stack_cfg(cfg, stack, minion_id, pillar, namespace): basedir, filename = os.path.split(cfg) lookup = TemplateLookup(directories=[basedir]) tops = lookup.get_template(filename).render(__opts__=__opts__, __salt__=__salt__, __grains__=__grains__, minion_id=minion_id, pillar=pillar, stack=stack) for path in _parse_top_cfg(tops): dirs = [basedir] if path.startswith('/'): dirs += ['/'] lookup = TemplateLookup(directories=dirs) try: p = lookup.get_template(path).render(__opts__=__opts__, __salt__=__salt__, __grains__=__grains__, minion_id=minion_id, pillar=pillar, stack=stack) obj = yaml.safe_load(p) if not isinstance(obj, dict): log.info('Ignoring Stack template "{0}": Can\'t parse ' 'as a valid yaml dictionary'.format(path)) continue if namespace: for sub in namespace.split(':')[::-1]: obj = {sub: obj} stack = _merge_dict(stack, obj) log.info('Stack template {0} parsed'.format(path)) except exceptions.TopLevelLookupException as e: log.info('Stack template "{0}" not found.'.format(path)) continue except Exception as e: log.info('Ignoring Stack template "{0}":'.format(path)) log.info('{0}'.format(exceptions.text_error_template().render())) continue return stack
def render_tale(talefile, tales): talelink = tale_link(talefile) print('Building tale/{}/index.html'.format(talelink)) os.makedirs('build/tale/{}'.format(talelink), exist_ok=True) with open('build/tale/{}/index.html'.format(talelink), 'wt') as htmlfile: lookup = TemplateLookup(directories=['src/templates'], input_encoding='utf-8', preprocessor=pug_preprocessor) tale = tales[talelink] tale.find_title() htmlfile.write(lookup.get_template('tale.pug').render( tale=tale ))
class View(object): def __init__(self, view_search_folder): self.lookup_o = TemplateLookup(directories=view_search_folder, input_encoding='utf-8') def load(self, template, data_opl={}): data_opl['_routes'] = RouterConfig.getAllRoutes() data_opl['_notifications'] = self.__getNotificationSessions() data_opl['_currentUrl'] = cherrypy.url() return self.__render(template, data_opl) def __render(self, template_spl, data_opl): header = self.__render_header(data_opl) footer = self.__render_footer(data_opl) content = self.__render_template(template_spl, data_opl) self.__cleanupNotificationSessions() return header + content + footer def __render_header(self, data_opl): return self.__render_template('_partials.header', data_opl) def __render_footer(self, data_opl): return self.__render_template('_partials.footer', data_opl) def __render_template(self, template_spl, data_opl): template_spl = template_spl.replace('.', '/') template = self.lookup_o.get_template(template_spl + AppConfig.view_extension) rendered = template.render(data=data_opl) return rendered def __cleanupNotificationSessions(self): for session_key, session_value in enumerate( list(cherrypy.session.items())): if session_value[0].startswith('notifications_'): cherrypy.session.pop(session_value[0]) def __getNotificationSessions(self): sessionData = {} for session_key, session_value in enumerate(cherrypy.session.items()): if session_value[0].startswith('notifications_'): notification_type = session_value[0].replace( 'notifications_', '') notification_message = session_value[1] sessionData[notification_type] = notification_message return sessionData
class TGPlugin(object): """TurboGears compatible Template Plugin.""" def __init__(self, extra_vars_func=None, options=None, extension="mak"): self.extra_vars_func = extra_vars_func self.extension = extension if not options: options = {} # Pull the options out and initialize the lookup lookup_options = {} for k, v in options.items(): if k.startswith("mako."): lookup_options[k[5:]] = v elif k in ["directories", "filesystem_checks", "module_directory"]: lookup_options[k] = v self.lookup = TemplateLookup(**lookup_options) self.tmpl_options = {} # transfer lookup args to template args, based on those available # in getargspec for kw in compat.inspect_getargspec(Template.__init__)[0]: if kw in lookup_options: self.tmpl_options[kw] = lookup_options[kw] def load_template(self, templatename, template_string=None): """Loads a template from a file or a string""" if template_string is not None: return Template(template_string, **self.tmpl_options) # Translate TG dot notation to normal / template path if "/" not in templatename: templatename = ("/" + templatename.replace(".", "/") + "." + self.extension) # Lookup template return self.lookup.get_template(templatename) def render( self, info, format="html", fragment=False, template=None # noqa ): if isinstance(template, compat.string_types): template = self.load_template(template) # Load extra vars func if provided if self.extra_vars_func: info.update(self.extra_vars_func()) return template.render(**info)
def build_mako(): env = { '_': _, 'config': config, 'streams': streams, 'games': games, 'categories': categories } lookup = TemplateLookup(directories=['./src/mako'], input_encoding='utf-8') # Recreate required directories if not os.path.isdir(_('')): os.mkdir(_('')) # Legacy cleanup for dp in ['links', 'r']: if os.path.isdir(_(dp)): shutil.rmtree(_(dp)) for fp in ['search.html', 'missing.html']: if os.path.exists(_(fp)): os.unlink(_(fp)) # Generate index.html with open(_('index.html'), 'w') as out: t = lookup.get_template('/index.mako') out.write(t.render(**env)) # Generate robots.txt with open(_('robots.txt'), 'w') as out: t = lookup.get_template('/robots.mako') out.write(t.render(**env)) # Generate sitemap.xml with open(_('sitemap.xml'), 'w') as out: t = lookup.get_template('/sitemap.mako') out.write(t.render(**env))