Exemple #1
0
 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 北京.'))
Exemple #2
0
    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"]
        )
Exemple #3
0
    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"])
Exemple #4
0
 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'))
Exemple #5
0
 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 北京.')
     )
Exemple #6
0
    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'))
Exemple #7
0
 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'))
Exemple #8
0
    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)
Exemple #9
0
    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)
Exemple #10
0
    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'}

        )
Exemple #11
0
 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")]
     )
Exemple #12
0
    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)
Exemple #13
0
    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'
                      })
Exemple #14
0
    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)
Exemple #15
0
    def test_utf8_format_errors_no_pygments(self):
        """test that htmlentityreplace formatting is applied to
           errors reported with format_errors=True"""

        l = TemplateLookup(format_errors=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">${&#39;привет&#39; + foobar}</div>'\
                in result_lines(l.get_template("foo.html").render().decode('utf-8'))
        else:
            assert '${u&#39;&#x43F;&#x440;&#x438;&#x432;&#x435;'\
                   '&#x442;&#39; + foobar}' in \
                result_lines(l.get_template("foo.html").render().decode('utf-8'))
Exemple #16
0
    def test_utf8_format_errors_pygments(self):
        """test that htmlentityreplace formatting is applied to
           errors reported with format_errors=True"""

        l = TemplateLookup(format_errors=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 '&#39;привет&#39;</span>' in \
                l.get_template("foo.html").render().decode('utf-8')
        else:
            assert 'u&#39;&#x43F;&#x440;&#x438;&#x432;'\
                    '&#x435;&#x442;&#39;</span>' in \
                l.get_template("foo.html").render().decode('utf-8')
Exemple #17
0
    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")
        ])
Exemple #18
0
    def test_builtin_names_dont_clobber_defaults_in_includes(self):
        lookup = TemplateLookup()
        lookup.put_string("test.choco",
        """
        <%include file="test1.choco"/>

        """)

        lookup.put_string("test1.choco", """
        <%page args="id='foo'"/>

        ${id}
        """)

        for template in ("test.choco", "test1.choco"):
            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>"
Exemple #19
0
    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')
        )
Exemple #20
0
 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"
Exemple #21
0
 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"
Exemple #22
0
def choco(dirname, verbose=False):
    from choco.template import Template
    from choco.lookup import TemplateLookup
    disable_unicode = (sys.version_info < (3,))
    lookup = TemplateLookup(directories=[dirname], filesystem_checks=False, disable_unicode=disable_unicode)
    template = lookup.get_template('template.html')
    def render():
        return template.render(title=TITLE, user=USER, list_items=U_ITEMS)
    if verbose:
        print(template.code + " " + render())
    return render
Exemple #23
0
 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"
Exemple #24
0
 def test_lookup(self):
     l = TemplateLookup(cache_impl='mock')
     l.put_string("x", """
         <%page cached="True" />
         ${y}
     """)
     t = l.get_template("x")
     self._install_mock_cache(t)
     assert result_lines(t.render(y=5)) == ["5"]
     assert result_lines(t.render(y=7)) == ["5"]
     assert isinstance(t.cache.impl, MockCacheImpl)
Exemple #25
0
 def test_lookup(self):
     l = TemplateLookup(cache_impl='mock')
     l.put_string(
         "x", """
         <%page cached="True" />
         ${y}
     """)
     t = l.get_template("x")
     self._install_mock_cache(t)
     assert result_lines(t.render(y=5)) == ["5"]
     assert result_lines(t.render(y=7)) == ["5"]
     assert isinstance(t.cache.impl, MockCacheImpl)
Exemple #26
0
    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,
        )
Exemple #27
0
class ChocoBridge(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_errors=True,
        )

    def render(self, template, context):
        template = template.replace(".html", ".choco")
        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'] = "choco-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.choco"
            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.choco"

        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)
Exemple #28
0
    def test_builtin_names_dont_clobber_defaults_in_includes(self):
        lookup = TemplateLookup()
        lookup.put_string(
            "test.choco", """
        <%include file="test1.choco"/>

        """)

        lookup.put_string(
            "test1.choco", """
        <%page args="id='foo'"/>

        ${id}
        """)

        for template in ("test.choco", "test1.choco"):
            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>"
Exemple #29
0
    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,
        )
Exemple #30
0
    def test_format_errors_pygments(self):
        l = TemplateLookup(format_errors=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()
Exemple #31
0
    def test_format_errors_no_pygments(self):
        l = TemplateLookup(format_errors=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())
Exemple #32
0
 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"
Exemple #33
0
 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"
Exemple #34
0
 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"
Exemple #35
0
    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)
Exemple #36
0
 def test_within_ccall(self):
     lookup = TemplateLookup()
     lookup.put_string("a", """this is a""")
     lookup.put_string("b", """
     <%def name="bar()">
         bar: ${caller.body()}
         <%include file="a"/>
     </%def>
     """)
     lookup.put_string("c", """
     <%namespace name="b" file="b"/>
     <%b:bar>
         calling bar
     </%b:bar>
     """)
     assert flatten_result(lookup.get_template("c").render()) == "bar: calling bar this is a"
Exemple #37
0
    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,
        )
Exemple #38
0
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('choco.'):
                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):
        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)
Exemple #39
0
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('choco.'):
                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):
        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)
Exemple #40
0
    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
        )
Exemple #41
0
    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,
        )
Exemple #42
0
class ChocoLoader(object):
    """Choco Tempatle Engine Loader


    :param  list[str] directories: the choco template root paths
    :param  kwargs: the more settings for choco template

    :param UIContainer ui_container: the ui template container (default: {None})
    :param string module_directory: the choco template module cache path (default: {None})
    :param bool filesystem_checks: when ``True`` the choco loader will check the template file and reload the last modify template(default: {False})

    """

    def __init__(self, directories, ui_container=None, module_directory=None, filesystem_checks=False, **kwargs):
        self._lookup = TemplateLookup(directories=directories,
                                      ui_container=ui_container,
                                      filesystem_checks=filesystem_checks,
                                      module_directory=module_directory,
                                      input_encoding='utf-8',
                                      output_encoding='utf-8',
                                      default_filters=['decode.utf8'],
                                      **kwargs)

    def load(self, name, parent_path=None):
        """Load the template by name"""
        return self._create_template(name)

    def _create_template(self, name):
        """The tornado temaple loader load the real tempalte


        :param name: the template path name
        :type name:  string
        :returns: the choco template instance
        :rtype: {Template}
        """
        template = self._lookup.get_template(name)
        template.generate = template.render

        return template

    def reset(self):
        """Reset the template engine cache"""
        pass
Exemple #43
0
 def test_within_ccall(self):
     lookup = TemplateLookup()
     lookup.put_string("a", """this is a""")
     lookup.put_string(
         "b", """
     <%def name="bar()">
         bar: ${caller.body()}
         <%include file="a"/>
     </%def>
     """)
     lookup.put_string(
         "c", """
     <%namespace name="b" file="b"/>
     <%b:bar>
         calling bar
     </%b:bar>
     """)
     assert flatten_result(
         lookup.get_template("c").render()) == "bar: calling bar this is a"
Exemple #44
0
    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)
Exemple #45
0
    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)
Exemple #46
0
    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)
Exemple #47
0
    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)
Exemple #48
0
    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'}

        )
Exemple #49
0
    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'
                      })
Exemple #50
0
 def test_via_lookup(self):
     tl = TemplateLookup(lexer_cls=self._fixture())
     tl.put_string("foo", "foo")
     t = tl.get_template("foo")
     self._test_custom_lexer(t)
Exemple #51
0
 def test_via_lookup(self):
     tl = TemplateLookup(lexer_cls=self._fixture())
     tl.put_string("foo", "foo")
     t = tl.get_template("foo")
     self._test_custom_lexer(t)