Exemple #1
0
    def test_module_roundtrip(self):
        lookup = TemplateLookup()

        template = Template("""
        <%inherit file="base.html"/>

        % for x in range(5):
            ${x}
        % endfor
""",
                            lookup=lookup)

        base = Template("""
        This is base.
        ${self.body()}
""",
                        lookup=lookup)

        lookup.put_template("base.html", base)
        lookup.put_template("template.html", template)

        assert result_lines(
            template.render()) == ["This is base.", "0", "1", "2", "3", "4"]

        lookup = TemplateLookup()
        template = ModuleTemplate(template.module, lookup=lookup)
        base = ModuleTemplate(base.module, lookup=lookup)

        lookup.put_template("base.html", base)
        lookup.put_template("template.html", template)

        assert result_lines(
            template.render()) == ["This is base.", "0", "1", "2", "3", "4"]
Exemple #2
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 #3
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 #4
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 #5
0
    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)
Exemple #6
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 #7
0
def cmdline(argv=None):

    parser = ArgumentParser("usage: %prog [FILENAME]")
    parser.add_argument(
        "--var",
        default=[],
        action="append",
        help="variable (can be used multiple times, use name=value)")
    parser.add_argument(
        "--template-dir",
        default=[],
        action="append",
        help="Directory to use for template lookup (multiple "
        "directories may be provided). If not given then if the "
        "template is read from stdin, the value defaults to be "
        "the current directory, otherwise it defaults to be the "
        "parent directory of the file provided.")
    parser.add_argument('input', nargs='?', default='-')

    options = parser.parse_args(argv)
    if options.input == '-':
        lookup_dirs = options.template_dir or ["."]
        lookup = TemplateLookup(lookup_dirs)
        try:
            template = Template(sys.stdin.read(), lookup=lookup)
        except:
            _exit()
    else:
        filename = options.input
        if not isfile(filename):
            raise SystemExit("error: can't find %s" % filename)
        lookup_dirs = options.template_dir or [dirname(filename)]
        lookup = TemplateLookup(lookup_dirs)
        try:
            template = Template(filename=filename, lookup=lookup)
        except:
            _exit()

    kw = dict([varsplit(var) for var in options.var])
    try:
        print(template.render(**kw))
    except:
        _exit()
Exemple #8
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 #9
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 #10
0
    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,
        )
Exemple #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
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 #20
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 #21
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 #22
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 #23
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 #24
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 #25
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 #26
0
    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]
Exemple #27
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 #28
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 #29
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 #30
0
    def test_dynamic_key_with_imports(self):
        lookup = TemplateLookup()
        lookup.put_string(
            "foo.html", """
        <%!
            callcount = [0]
        %>
        <%namespace file="ns.html" import="*"/>
        <%page cached="True" cache_key="${foo}"/>
        this is foo
        <%
        callcount[0] += 1
        %>
        callcount: ${callcount}
""")
        lookup.put_string("ns.html", """""")
        t = lookup.get_template("foo.html")
        m = self._install_mock_cache(t)
        t.render(foo='somekey')
        t.render(foo='somekey')
        assert result_lines(
            t.render(foo='somekey')) == ["this is foo", "callcount: [1]"]
        assert m.kwargs == {}