def test_strict(self): t = Template(""" % if x is UNDEFINED: undefined % else: x: ${x} % endif """, strict_undefined=True) assert result_lines(t.render(x=12)) == ['x: 12'] assert_raises( NameError, t.render, y=12 ) l = TemplateLookup(strict_undefined=True) l.put_string("a", "some template") l.put_string("b", """ <%namespace name='a' file='a' import='*'/> % if x is UNDEFINED: undefined % else: x: ${x} % endif """) assert result_lines(t.render(x=12)) == ['x: 12'] assert_raises( NameError, t.render, y=12 )
def create_lookup(): lookup = TemplateLookup() import mycartable.qrc for file in QDir(":/templates").entryInfoList(): lookup.put_string(file.fileName(), read_qrc(file.absoluteFilePath())) return lookup
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 util.py3k: l.put_string("foo.html", """# -*- coding: utf-8 -*-\n${'привет' + foobar}""") else: l.put_string("foo.html", """# -*- coding: utf-8 -*-\n${u'привет' + foobar}""") if util.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'))
def test_inherited_block_nested_inner_only(self): l = TemplateLookup() l.put_string( "index", """ <%inherit file="base"/> <%block name="title"> index title </%block> """) l.put_string( "base", """ above <%block name="header"> base header <%block name="title"> the title </%block> </%block> ${next.body()} below """) self._do_test(l.get_template("index"), ["above", "base header", "index title", "below"], filters=result_lines)
def test_inherits(self): lookup = TemplateLookup() lookup.put_string( "base.tmpl", """ <%page args="bar" /> ${bar} ${pageargs['foo']} ${self.body(**pageargs)} """, ) lookup.put_string( "index.tmpl", """ <%inherit file="base.tmpl" /> <%page args="variable" /> ${variable} """, ) self._do_test( lookup.get_template("index.tmpl"), "bar foo var", filters=flatten_result, template_args={"variable": "var", "bar": "bar", "foo": "foo"}, )
def test_inherits(self): lookup = TemplateLookup() lookup.put_string( "base.tmpl", """ <%page args="bar" /> ${bar} ${pageargs['foo']} ${self.body(**pageargs)} """, ) lookup.put_string( "index.tmpl", """ <%inherit file="base.tmpl" /> <%page args="variable" /> ${variable} """, ) self._do_test( lookup.get_template("index.tmpl"), "bar foo var", filters=flatten_result, template_args={ "variable": "var", "bar": "bar", "foo": "foo" }, )
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'))
def test_utf8_format_exceptions_no_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 ( '<div class="sourceline">${'привет' + foobar}</div>' in result_lines( l.get_template("foo.html").render().decode("utf-8") ) ) else: assert ( "${u'приве" "т' + foobar}" in result_lines( l.get_template("foo.html").render().decode("utf-8") ) )
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>")
def test_def_overridden_by_block(self): l = TemplateLookup() l.put_string( "index", """ <%inherit file="base"/> <%block name="header"> inner header </%block> """, ) l.put_string( "base", """ above ${self.header()} <%def name="header()"> the header </%def> ${next.body()} below """, ) self._do_test( l.get_template("index"), ["above", "inner header", "below"], filters=result_lines, )
def test_no_conflict_nested_one(self): l = TemplateLookup() l.put_string( "index", """ <%inherit file="base"/> <%block> <%block name="header"> inner header </%block> </%block> """, ) l.put_string( "base", """ above <%block name="header"> the header </%block> ${next.body()} below """, ) self._do_test( l.get_template("index"), ["above", "inner header", "below"], filters=result_lines, )
def test_noninherited_block_no_render(self): l = TemplateLookup() l.put_string( "index", """ <%inherit file="base"/> <%block name="some_thing"> some thing </%block> """, ) l.put_string( "base", """ above <%block name="header"> the header </%block> ${next.body()} below """, ) self._do_test( l.get_template("index"), ["above", "the header", "some thing", "below"], filters=result_lines, )
def compile_template(template_dict, template_name): """Compile template.""" lookup = TemplateLookup(filesystem_checks=False) for name, template in template_dict.items(): lookup.put_string(name, template) compiled = lookup.get_template(template_name) return compiled
def test_inherited_block_nested_inner_only(self): l = TemplateLookup() l.put_string("index", """ <%inherit file="base"/> <%block name="title"> index title </%block> """ ) l.put_string("base",""" above <%block name="header"> base header <%block name="title"> the title </%block> </%block> ${next.body()} below """) self._do_test(l.get_template("index"), ["above", "base header", "index title", "below"], filters=result_lines)
def test_lookup(self): l = TemplateLookup(cache_impl='mock') l.put_string("x", """ <%page cached="True" /> ${y} """) t = l.get_template("x") assert result_lines(t.render(y=5)) == ["5"] assert result_lines(t.render(y=7)) == ["5"] assert isinstance(t.cache.impl, MockCacheImpl)
def test_utf8_format_exceptions(self): """test that htmlentityreplace formatting is applied to exceptions reported with format_exceptions=True""" l = TemplateLookup(format_exceptions=True) l.put_string("foo.html", """# -*- coding: utf-8 -*- ${u'привет' + foobar} """) assert '''<div class="highlight">2 ${u\'привет\' + foobar}</div>''' in result_lines(l.get_template("foo.html").render())
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) l.put_string("foo.html", """# -*- coding: utf-8 -*-\n${'привет' + foobar}""") assert "'привет'</span>" in l.get_template( "foo.html").render().decode("utf-8")
def test_lookup(self): l = TemplateLookup(cache_impl='mock') l.put_string( "x", """ <%page cached="True" /> ${y} """) t = l.get_template("x") assert result_lines(t.render(y=5)) == ["5"] assert result_lines(t.render(y=7)) == ["5"] assert isinstance(t.cache.impl, MockCacheImpl)
def test_basic(self): lookup = TemplateLookup() lookup.put_string("a", """ this is a <%include file="b" args="a=3,b=4,c=5"/> """) lookup.put_string("b", """ <%page args="a,b,c"/> this is b. ${a}, ${b}, ${c} """) assert flatten_result(lookup.get_template("a").render()) == "this is a this is b. 3, 4, 5"
def test_localargs(self): lookup = TemplateLookup() lookup.put_string("a", """ this is a <%include file="b" args="a=a,b=b,c=5"/> """) lookup.put_string("b", """ <%page args="a,b,c"/> this is b. ${a}, ${b}, ${c} """) assert flatten_result(lookup.get_template("a").render(a=7,b=8)) == "this is a this is b. 7, 8, 5"
def test_include_withargs(self): lookup = TemplateLookup() lookup.put_string("a", """ this is a <%include file="${i}" args="c=5, **context.kwargs"/> """) lookup.put_string("b", """ <%page args="a,b,c"/> this is b. ${a}, ${b}, ${c} """) assert flatten_result(lookup.get_template("a").render(a=7,b=8,i='b')) == "this is a this is b. 7, 8, 5"
def get_template_lookup(): try: db_template = sqlm.EmailTemplate.query.all() _lookup = TemplateLookup() for template in db_template: _lookup.put_string(template.name, template.template) return _lookup except IndexError: return False
def test_loop_disabled_lookup(self): l = TemplateLookup(enable_loop=False) l.put_string("x", """ the loop: ${loop} """) self._do_test( l.get_template("x"), "the loop: hi", template_args=dict(loop='hi'), filters=flatten_result, )
def test_format_exceptions(self): l = TemplateLookup(format_exceptions=True) l.put_string("foo.html", """ <%inherit file="base.html"/> ${foobar} """) l.put_string("base.html", """ ${self.body()} """) assert '<div class="sourceline">${foobar}</div>' in result_lines(l.get_template("foo.html").render())
class MakoPlugin: def __init__(self): self.lookup = TemplateLookup(directories=['.'], output_encoding='utf-8', encoding_errors='replace') def fill_template(self, template, bits, result): self.lookup.put_string('actual', template) t = self.lookup.get_template('actual') try: r = t.render_unicode(**bits) except: r = exceptions.html_error_template().render() result.value = r return False
def test_format_exceptions_pygments(self): l = TemplateLookup(format_exceptions=True) l.put_string("foo.html", """ <%inherit file="base.html"/> ${foobar} """) l.put_string("base.html", """ ${self.body()} """) assert '<div class="sourceline"><table class="syntax-highlightedtable">' in \ l.get_template("foo.html").render_unicode()
def test_include_error_handler(self): def handle(context, error): context.write('include error') return True lookup = TemplateLookup(include_error_handler=handle) lookup.put_string("a", """ this is a. <%include file="b"/> """) lookup.put_string("b", """ this is b ${1/0} end. """) assert flatten_result(lookup.get_template("a").render()) == "this is a. this is b include error"
def test_format_exceptions(self): l = TemplateLookup(format_exceptions=True) l.put_string("foo.html", """ <%inherit file="base.html"/> ${foobar} """) l.put_string("base.html", """ ${self.body()} """) assert '<div class="sourceline">${foobar}</div>' in \ result_lines(l.get_template("foo.html").render_unicode())
def test_loop_disabled_lookup(self): l = TemplateLookup(enable_loop=False) l.put_string("x", """ the loop: ${loop} """ ) self._do_test( l.get_template("x"), "the loop: hi", template_args=dict(loop='hi'), filters=flatten_result, )
class MakoBridge(TemplateBridge): def init(self, builder, *args, **kw): self.jinja2_fallback = BuiltinTemplateLoader() self.jinja2_fallback.init(builder, *args, **kw) builder.config.html_context['release_date'] = builder.config['release_date'] builder.config.html_context['site_base'] = builder.config['site_base'] self.lookup = TemplateLookup(directories=builder.config.templates_path, #format_exceptions=True, imports=[ "from builder import util" ] ) if rtd: # RTD layout, imported from sqlalchemy.org import urllib2 template = urllib2.urlopen(builder.config['site_base'] + "/docs_adapter.mako").read() self.lookup.put_string("docs_adapter.mako", template) setup_ctx = urllib2.urlopen(builder.config['site_base'] + "/docs_adapter.py").read() lcls = {} exec(setup_ctx, lcls) self.setup_ctx = lcls['setup_context'] def setup_ctx(self, context): pass def render(self, template, context): template = template.replace(".html", ".mako") context['prevtopic'] = context.pop('prev', None) context['nexttopic'] = context.pop('next', None) # local docs layout context['rtd'] = False context['toolbar'] = False context['base'] = "static_base.mako" # override context attributes self.setup_ctx(context) 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)
def bench_mako(runner, table_size, nparagraph, img_count): lookup = TemplateLookup() lookup.put_string('base.mako', BASE_TEMPLATE) lookup.put_string('page.mako', PAGE_TEMPLATE) template = Template(CONTENT_TEMPLATE, lookup=lookup) table = [xrange(table_size) for i in xrange(table_size)] paragraphs = xrange(nparagraph) title = 'Hello world!' func = functools.partial(template.render, table=table, paragraphs=paragraphs, lorem=LOREM_IPSUM, title=title, img_count=img_count, xrange=xrange) runner.bench_func('mako', func)
def test_loop_enabled_override_lookup(self): l = TemplateLookup() l.put_string( "x", """ <%page enable_loop="True" /> % for i in (1, 2, 3): ${i} ${loop.index} % endfor """) self._do_test( l.get_template("x"), "1 0 2 1 3 2", template_args=dict(), filters=flatten_result, )
def test_block_pageargs(self): l = TemplateLookup() l.put_string( "caller", """ <%include file="callee" args="val1='3', val2='4'"/> """) l.put_string( "callee", """ <%block name="foob"> foob, ${pageargs['val1']}, ${pageargs['val2']} </%block> """) self._do_test(l.get_template("caller"), ['foob, 3, 4'], filters=result_lines)
def test_loop_enabled_override_lookup(self): l = TemplateLookup() l.put_string("x", """ <%page enable_loop="True" /> % for i in (1, 2, 3): ${i} ${loop.index} % endfor """ ) self._do_test( l.get_template("x"), "1 0 2 1 3 2", template_args=dict(), filters=flatten_result, )
def test_utf8_format_exceptions(self): """test that htmlentityreplace formatting is applied to exceptions reported with format_exceptions=True""" l = TemplateLookup(format_exceptions=True) if util.py3k: l.put_string("foo.html", """# -*- coding: utf-8 -*-\n${'привет' + foobar}""") else: l.put_string("foo.html", """# -*- coding: utf-8 -*-\n${u'привет' + foobar}""") if util.py3k: assert u'<div class="sourceline">${'привет' + foobar}</div>'\ in result_lines(l.get_template("foo.html").render().decode('utf-8')) else: assert '<div class="highlight">2 ${u'пр'\ 'ивет' + foobar}</div>' \ in result_lines(l.get_template("foo.html").render().decode('utf-8'))
def test_utf8_format_exceptions(self): """test that htmlentityreplace formatting is applied to exceptions reported with format_exceptions=True""" l = TemplateLookup(format_exceptions=True) if util.py3k: l.put_string("foo.html", """# -*- coding: utf-8 -*-\n${'привет' + foobar}""") else: l.put_string("foo.html", """# -*- coding: utf-8 -*-\n${u'привет' + foobar}""") if util.py3k: assert u'<div class="sourceline">${\'привет\' + foobar}</div>'\ in result_lines(l.get_template("foo.html").render().decode('utf-8')) else: assert '<div class="highlight">2 ${u\'пр'\ 'ивет\' + foobar}</div>' \ in result_lines(l.get_template("foo.html").render().decode('utf-8'))
def test_template_lookup(self): try: from mako.lookup import TemplateLookup except ImportError: return lookup = TemplateLookup() lookup.put_string("base.html", ''' <% import time time.sleep(0.01) %> <html><body></body></html> ''') template = lookup.get_template("base.html") template.render_unicode() stats, result = get_local_storage(local_timing).get_thread_stats() self.assertEqual(len(result), 1)
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 ''привет'</span>' in \ l.get_template("foo.html").render().decode('utf-8') else: assert ''прив'\ 'ет'</span>' in \ l.get_template("foo.html").render().decode('utf-8')
def test_block_pageargs(self): l = TemplateLookup() l.put_string("caller", """ <%include file="callee" args="val1='3', val2='4'"/> """) l.put_string("callee", """ <%block name="foob"> foob, ${pageargs['val1']}, ${pageargs['val2']} </%block> """) self._do_test( l.get_template("caller"), [u'foob, 3, 4'], filters=result_lines )
def test_utf8_format_exceptions_no_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 '<div class="sourceline">${'привет' + foobar}</div>'\ in result_lines(l.get_template("foo.html").render().decode('utf-8')) else: assert '${u'приве'\ 'т' + foobar}' in \ result_lines(l.get_template("foo.html").render().decode('utf-8'))
def test_viakwargs(self): lookup = TemplateLookup() lookup.put_string( "a", """ this is a <%include file="b" args="c=5, **context.kwargs"/> """, ) lookup.put_string( "b", """ <%page args="a,b,c"/> this is b. ${a}, ${b}, ${c} """, ) # print lookup.get_template("a").code assert flatten_result(lookup.get_template("a").render(a=7, b=8)) == "this is a this is b. 7, 8, 5"
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>"
def test_format_exceptions_pygments(self): l = TemplateLookup(format_exceptions=True) l.put_string("foo.html", """ <%inherit file="base.html"/> ${foobar} """) l.put_string("base.html", """ ${self.body()} """) assert '<div class="sourceline"><table class="syntax-highlightedtable">'\ '<tr><td class="linenos"><div class="linenodiv"><pre>3</pre>'\ '</div></td><td class="code"><div class="syntax-highlighted">'\ '<pre><span class="err">$</span><span class="p">{</span>'\ '<span class="n">foobar</span><span class="p">}</span>' in \ result_lines(l.get_template("foo.html").render_unicode())
def test_viakwargs(self): lookup = TemplateLookup() lookup.put_string( "a", """ this is a <%include file="b" args="c=5, **context.kwargs"/> """, ) lookup.put_string( "b", """ <%page args="a,b,c"/> this is b. ${a}, ${b}, ${c} """, ) # print lookup.get_template("a").code assert (flatten_result(lookup.get_template("a").render( a=7, b=8)) == "this is a this is b. 7, 8, 5")
def test_mako(count): lookup = TemplateLookup() lookup.put_string('base.mako', BASE_TEMPLATE) lookup.put_string('page.mako', PAGE_TEMPLATE) template = Template(CONTENT_TEMPLATE, lookup=lookup) table = [xrange(150) for i in xrange(150)] paragraphs = xrange(50) title = 'Hello world!' times = [] for i in range(count): t0 = time.time() data = template.render(table=table, paragraphs=paragraphs, lorem=LOREM_IPSUM, title=title, img_count=50) t1 = time.time() times.append(t1-t0) return times
def gen_hook_function_code(data, templates={}): lookup = TemplateLookup(strict_undefined=True) lookup.put_string("hook", HOOK_TEMPLATE) lookup.put_string("pre", PREHOOK_TEMPLATE) lookup.put_string("post", POSTHOOK_TEMPLATE) tm = lookup.get_template(data["hook"].type) return tm.render(**data)
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'} )
def test_two_levels_one(self): l = TemplateLookup() l.put_string("index", """ <%inherit file="middle"/> <%block name="header"> index header </%block> <%block> index anon </%block> """ ) l.put_string("middle", """ <%inherit file="base"/> <%block> middle anon </%block> ${next.body()} """) l.put_string("base",""" above <%block name="header"> the header </%block> ${next.body()} below """) self._do_test(l.get_template("index"), ["above", "index header", "middle anon", "index anon", "below"], filters=result_lines)
def test_block_overridden_by_def(self): l = TemplateLookup() l.put_string("index", """ <%inherit file="base"/> <%def name="header()"> inner header </%def> """ ) l.put_string("base",""" above <%block name="header"> the header </%block> ${next.body()} below """) self._do_test(l.get_template("index"), ["above", "inner header", "below"], filters=result_lines)