Python mako.lookup.TemplateLookup() Examples

The following are 30 code examples of mako.lookup.TemplateLookup(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module mako.lookup , or try the search function .
Example #1
Source File: test_loop.py    From mako with MIT License 6 votes vote down vote up
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,
        ) 
Example #2
Source File: turbogears.py    From teleport with Apache License 2.0 6 votes vote down vote up
def __init__(self, extra_vars_func=None, options=None, extension='mak'):
        self.extra_vars_func = extra_vars_func
        self.extension = extension
        if not options:
            options = {}

        # Pull the options out and initialize the lookup
        lookup_options = {}
        for k, v in options.items():
            if k.startswith('mako.'):
                lookup_options[k[5:]] = v
            elif k in ['directories', 'filesystem_checks', 'module_directory']:
                lookup_options[k] = v
        self.lookup = TemplateLookup(**lookup_options)

        self.tmpl_options = {}
        # transfer lookup args to template args, based on those available
        # in getargspec
        for kw in compat.inspect_getargspec(Template.__init__)[0]:
            if kw in lookup_options:
                self.tmpl_options[kw] = lookup_options[kw] 
Example #3
Source File: turbogears.py    From teleport with Apache License 2.0 6 votes vote down vote up
def __init__(self, extra_vars_func=None, options=None, extension="mak"):
        self.extra_vars_func = extra_vars_func
        self.extension = extension
        if not options:
            options = {}

        # Pull the options out and initialize the lookup
        lookup_options = {}
        for k, v in options.items():
            if k.startswith("mako."):
                lookup_options[k[5:]] = v
            elif k in ["directories", "filesystem_checks", "module_directory"]:
                lookup_options[k] = v
        self.lookup = TemplateLookup(**lookup_options)

        self.tmpl_options = {}
        # transfer lookup args to template args, based on those available
        # in getargspec
        for kw in compat.inspect_getargspec(Template.__init__)[0]:
            if kw in lookup_options:
                self.tmpl_options[kw] = lookup_options[kw] 
Example #4
Source File: test_exceptions.py    From mako with MIT License 6 votes vote down vote up
def test_format_exceptions_no_pygments(self):
        l = TemplateLookup(format_exceptions=True)

        l.put_string(
            "foo.html",
            """
<%inherit file="base.html"/>
${foobar}
        """,
        )

        l.put_string(
            "base.html",
            """
        ${self.body()}
        """,
        )

        assert '<div class="sourceline">${foobar}</div>' in result_lines(
            l.get_template("foo.html").render_unicode()
        ) 
Example #5
Source File: test_exceptions.py    From mako with MIT License 6 votes vote down vote up
def test_utf8_format_exceptions_pygments(self):
        """test that htmlentityreplace formatting is applied to
           exceptions reported with format_exceptions=True"""

        l = TemplateLookup(format_exceptions=True)
        if compat.py3k:
            l.put_string(
                "foo.html", """# -*- coding: utf-8 -*-\n${'привет' + foobar}"""
            )
        else:
            l.put_string(
                "foo.html",
                """# -*- coding: utf-8 -*-\n${u'привет' + foobar}""",
            )

        if compat.py3k:
            assert "&#39;привет&#39;</span>" in l.get_template(
                "foo.html"
            ).render().decode("utf-8")
        else:
            assert (
                "&#39;&#x43F;&#x440;&#x438;&#x432;"
                "&#x435;&#x442;&#39;</span>"
            ) in l.get_template("foo.html").render().decode("utf-8") 
Example #6
Source File: test_exceptions.py    From mako with MIT License 6 votes vote down vote up
def test_module_block_line_number(self):
        l = TemplateLookup()
        l.put_string(
            "foo.html",
            """
<%!
def foo():
    msg = "Something went wrong."
    raise RuntimeError(msg)  # This is the line.
%>
${foo()}
            """,
        )
        t = l.get_template("foo.html")
        try:
            t.render()
        except:
            text_error = exceptions.text_error_template().render_unicode()
            assert 'File "foo.html", line 7, in render_body' in text_error
            assert 'File "foo.html", line 5, in foo' in text_error
            assert "raise RuntimeError(msg)  # This is the line." in text_error
        else:
            assert False 
Example #7
Source File: turbogears.py    From jbox with MIT License 6 votes vote down vote up
def __init__(self, extra_vars_func=None, options=None, extension='mak'):
        self.extra_vars_func = extra_vars_func
        self.extension = extension
        if not options:
            options = {}

        # Pull the options out and initialize the lookup
        lookup_options = {}
        for k, v in options.items():
            if k.startswith('mako.'):
                lookup_options[k[5:]] = v
            elif k in ['directories', 'filesystem_checks', 'module_directory']:
                lookup_options[k] = v
        self.lookup = TemplateLookup(**lookup_options)

        self.tmpl_options = {}
        # transfer lookup args to template args, based on those available
        # in getargspec
        for kw in compat.inspect_getargspec(Template.__init__)[0]:
            if kw in lookup_options:
                self.tmpl_options[kw] = lookup_options[kw] 
Example #8
Source File: turbogears.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, extra_vars_func=None, options=None, extension="mak"):
        self.extra_vars_func = extra_vars_func
        self.extension = extension
        if not options:
            options = {}

        # Pull the options out and initialize the lookup
        lookup_options = {}
        for k, v in options.items():
            if k.startswith("mako."):
                lookup_options[k[5:]] = v
            elif k in ["directories", "filesystem_checks", "module_directory"]:
                lookup_options[k] = v
        self.lookup = TemplateLookup(**lookup_options)

        self.tmpl_options = {}
        # transfer lookup args to template args, based on those available
        # in getargspec
        for kw in compat.inspect_getargspec(Template.__init__)[0]:
            if kw in lookup_options:
                self.tmpl_options[kw] = lookup_options[kw] 
Example #9
Source File: test_template.py    From mako with MIT License 6 votes vote down vote up
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"),
        ) 
Example #10
Source File: turbogears.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, extra_vars_func=None, options=None, extension="mak"):
        self.extra_vars_func = extra_vars_func
        self.extension = extension
        if not options:
            options = {}

        # Pull the options out and initialize the lookup
        lookup_options = {}
        for k, v in options.items():
            if k.startswith("mako."):
                lookup_options[k[5:]] = v
            elif k in ["directories", "filesystem_checks", "module_directory"]:
                lookup_options[k] = v
        self.lookup = TemplateLookup(**lookup_options)

        self.tmpl_options = {}
        # transfer lookup args to template args, based on those available
        # in getargspec
        for kw in compat.inspect_getargspec(Template.__init__)[0]:
            if kw in lookup_options:
                self.tmpl_options[kw] = lookup_options[kw] 
Example #11
Source File: test_template.py    From mako with MIT License 6 votes vote down vote up
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,
        )
        lookup.get_template("/modtest.html")
        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"),
            ],
        ) 
Example #12
Source File: turbogears.py    From teleport with Apache License 2.0 6 votes vote down vote up
def __init__(self, extra_vars_func=None, options=None, extension="mak"):
        self.extra_vars_func = extra_vars_func
        self.extension = extension
        if not options:
            options = {}

        # Pull the options out and initialize the lookup
        lookup_options = {}
        for k, v in options.items():
            if k.startswith("mako."):
                lookup_options[k[5:]] = v
            elif k in ["directories", "filesystem_checks", "module_directory"]:
                lookup_options[k] = v
        self.lookup = TemplateLookup(**lookup_options)

        self.tmpl_options = {}
        # transfer lookup args to template args, based on those available
        # in getargspec
        for kw in compat.inspect_getargspec(Template.__init__)[0]:
            if kw in lookup_options:
                self.tmpl_options[kw] = lookup_options[kw] 
Example #13
Source File: test_exceptions.py    From mako with MIT License 6 votes vote down vote up
def test_format_exceptions_pygments(self):
        l = TemplateLookup(format_exceptions=True)

        l.put_string(
            "foo.html",
            """
<%inherit file="base.html"/>
${foobar}
        """,
        )

        l.put_string(
            "base.html",
            """
        ${self.body()}
        """,
        )

        assert (
            '<div class="sourceline"><table class="syntax-highlightedtable">'
            in l.get_template("foo.html").render_unicode()
        ) 
Example #14
Source File: test_template.py    From mako with MIT License 6 votes vote down vote up
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"
        ) 
Example #15
Source File: turbogears.py    From mako with MIT License 6 votes vote down vote up
def __init__(self, extra_vars_func=None, options=None, extension="mak"):
        self.extra_vars_func = extra_vars_func
        self.extension = extension
        if not options:
            options = {}

        # Pull the options out and initialize the lookup
        lookup_options = {}
        for k, v in options.items():
            if k.startswith("mako."):
                lookup_options[k[5:]] = v
            elif k in ["directories", "filesystem_checks", "module_directory"]:
                lookup_options[k] = v
        self.lookup = TemplateLookup(**lookup_options)

        self.tmpl_options = {}
        # transfer lookup args to template args, based on those available
        # in getargspec
        for kw in compat.inspect_getargspec(Template.__init__)[0]:
            if kw in lookup_options:
                self.tmpl_options[kw] = lookup_options[kw] 
Example #16
Source File: test_namespace.py    From mako with MIT License 6 votes vote down vote up
def test_module(self):
        collection = lookup.TemplateLookup()

        collection.put_string(
            "main.html",
            """
        <%namespace name="comp" module="test.sample_module_namespace"/>

        this is main.  ${comp.foo1()}
        ${comp.foo2("hi")}
""",
        )

        assert (
            flatten_result(collection.get_template("main.html").render())
            == "this is main. this is foo1. this is foo2, x is hi"
        ) 
Example #17
Source File: test_namespace.py    From mako with MIT License 6 votes vote down vote up
def test_module_imports(self):
        collection = lookup.TemplateLookup()

        collection.put_string(
            "main.html",
            """
        <%namespace import="*" module="test.foo.test_ns"/>

        this is main.  ${foo1()}
        ${foo2("hi")}
""",
        )

        assert (
            flatten_result(collection.get_template("main.html").render())
            == "this is main. this is foo1. this is foo2, x is hi"
        ) 
Example #18
Source File: test_namespace.py    From mako with MIT License 6 votes vote down vote up
def test_module_imports_2(self):
        collection = lookup.TemplateLookup()

        collection.put_string(
            "main.html",
            """
        <%namespace import="foo1, foo2" module="test.foo.test_ns"/>

        this is main.  ${foo1()}
        ${foo2("hi")}
""",
        )

        assert (
            flatten_result(collection.get_template("main.html").render())
            == "this is main. this is foo1. this is foo2, x is hi"
        ) 
Example #19
Source File: test_namespace.py    From mako with MIT License 6 votes vote down vote up
def test_getattr(self):
        collection = lookup.TemplateLookup()
        collection.put_string(
            "main.html",
            """
            <%namespace name="foo" file="ns.html"/>
            <%
                 if hasattr(foo, 'lala'):
                     foo.lala()
                 if not hasattr(foo, 'hoho'):
                     context.write('foo has no hoho.')
            %>
         """,
        )
        collection.put_string(
            "ns.html",
            """
          <%def name="lala()">this is lala.</%def>
        """,
        )
        assert (
            flatten_result(collection.get_template("main.html").render())
            == "this is lala.foo has no hoho."
        ) 
Example #20
Source File: test_block.py    From mako with MIT License 6 votes vote down vote up
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
        ) 
Example #21
Source File: test_block.py    From mako with MIT License 6 votes vote down vote up
def test_block_args(self):
        l = TemplateLookup()
        l.put_string(
            "caller",
            """

            <%include file="callee" args="val1='3', val2='4'"/>

        """,
        )
        l.put_string(
            "callee",
            """
            <%page args="val1, val2"/>
            <%block name="foob" args="val1, val2">
                foob, ${val1}, ${val2}
            </%block>
        """,
        )
        self._do_test(
            l.get_template("caller"), ["foob, 3, 4"], filters=result_lines
        ) 
Example #22
Source File: test_template.py    From mako with MIT License 6 votes vote down vote up
def test_include_error_handler(self):
        def handle(context, error):
            context.write("include error")
            return True

        lookup = TemplateLookup(include_error_handler=handle)
        lookup.put_string(
            "a",
            """
            this is a.
            <%include file="b"/>
        """,
        )
        lookup.put_string(
            "b",
            """
            this is b ${1/0} end.
        """,
        )
        assert (
            flatten_result(lookup.get_template("a").render())
            == "this is a. this is b include error"
        ) 
Example #23
Source File: test_template.py    From mako with MIT License 6 votes vote down vote up
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"
        ) 
Example #24
Source File: test_template.py    From mako with MIT License 6 votes vote down vote up
def test_viakwargs(self):
        lookup = TemplateLookup()
        lookup.put_string(
            "a",
            """
            this is a
            <%include file="b" args="c=5, **context.kwargs"/>
        """,
        )
        lookup.put_string(
            "b",
            """
            <%page args="a,b,c"/>
            this is b.  ${a}, ${b}, ${c}
        """,
        )
        # print lookup.get_template("a").code
        assert (
            flatten_result(lookup.get_template("a").render(a=7, b=8))
            == "this is a this is b. 7, 8, 5"
        ) 
Example #25
Source File: test_template.py    From mako with MIT License 6 votes vote down vote up
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"
        ) 
Example #26
Source File: test_loop.py    From mako with MIT License 6 votes vote down vote up
def test_loop_disabled_override_lookup(self):
        l = TemplateLookup(enable_loop=False)
        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(loop="hi"),
            filters=flatten_result,
        ) 
Example #27
Source File: test_namespace.py    From mako with MIT License 6 votes vote down vote up
def test_dynamic(self):
        collection = lookup.TemplateLookup()

        collection.put_string(
            "a",
            """
        <%namespace name="b" file="${context['b_def']}"/>

        a.  b: ${b.body()}
""",
        )

        collection.put_string(
            "b",
            """
        b.
""",
        )

        eq_(
            flatten_result(collection.get_template("a").render(b_def="b")),
            "a. b: b.",
        ) 
Example #28
Source File: test_block.py    From mako with MIT License 5 votes vote down vote up
def test_no_conflict_nested_one(self):
        l = TemplateLookup()
        l.put_string(
            "index",
            """
                <%inherit file="base"/>
                <%block>
                    <%block name="header">
                        inner header
                    </%block>
                </%block>
            """,
        )
        l.put_string(
            "base",
            """
            above
            <%block name="header">
                the header
            </%block>

            ${next.body()}
            below
        """,
        )
        self._do_test(
            l.get_template("index"),
            ["above", "inner header", "below"],
            filters=result_lines,
        ) 
Example #29
Source File: test_cache.py    From mako with MIT License 5 votes vote down vote up
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 == {} 
Example #30
Source File: test_template.py    From mako with MIT License 5 votes vote down vote up
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"},
        )