示例#1
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
        )
示例#2
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"
        ]
示例#3
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 北京.'))
示例#4
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"])
示例#5
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'
                      })
示例#6
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)
示例#7
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,
        )
示例#8
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
示例#9
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)
示例#10
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,
        )
示例#11
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'))
示例#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)
示例#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'))
示例#14
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 北京.')
     )
示例#15
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"]
        )
示例#16
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,
        )
示例#17
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)
示例#18
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'}

        )
示例#19
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'))
示例#20
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,
        )
示例#21
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")]
     )
示例#22
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,
        )
示例#23
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)
示例#24
0
 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)
示例#25
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")
        ])
示例#26
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()
示例#27
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')
        )
示例#28
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]
示例#29
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)
示例#30
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)
示例#31
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)
示例#32
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"
示例#33
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"
示例#34
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')
示例#35
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'))
示例#36
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"
示例#37
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()
示例#38
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())
示例#39
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"
示例#40
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>"
示例#41
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)
示例#42
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)
示例#43
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"
示例#44
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"
示例#45
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"
示例#46
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>"
示例#47
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"
示例#48
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)
示例#49
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
示例#50
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]
示例#51
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
        )
示例#52
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 == {}
示例#53
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)
示例#54
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)
示例#55
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)