Beispiel #1
0
    def test_load_with_callback(self):
        fileobj = open(os.path.join(self.dirname, 'tmpl.html'), 'w')
        try:
            fileobj.write("""<html>
              <p>Hello</p>
            </html>""")
        finally:
            fileobj.close()

        def template_loaded(template):
            def my_filter(stream, ctxt):
                for kind, data, pos in stream:
                    if kind is TEXT and data.strip():
                        data = ', '.join([data, data.lower()])
                    yield kind, data, pos

            template.filters.insert(0, my_filter)

        loader = TemplateLoader([self.dirname], callback=template_loaded)
        tmpl = loader.load('tmpl.html')
        self.assertEqual(
            """<html>
              <p>Hello, hello</p>
            </html>""",
            tmpl.generate().render(encoding=None))

        # Make sure the filter is only added once
        tmpl = loader.load('tmpl.html')
        self.assertEqual(
            """<html>
              <p>Hello, hello</p>
            </html>""",
            tmpl.generate().render(encoding=None))
    def test_nested_include_in_fallback(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file1 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file1.write("""<div>Included</div>""")
            finally:
                file1.close()

            file2 = open(os.path.join(dirname, 'tmpl3.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
                  <xi:include href="tmpl2.html">
                    <xi:fallback>
                      <xi:include href="tmpl1.html" />
                    </xi:fallback>
                  </xi:include>
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname])
            tmpl = loader.load('tmpl3.html')
            self.assertEqual("""<html>
                  <div>Included</div>
                </html>""", tmpl.generate().render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Beispiel #3
0
    def test_load_with_callback(self):
        fileobj = open(os.path.join(self.dirname, 'tmpl.html'), 'w')
        try:
            fileobj.write("""<html>
              <p>Hello</p>
            </html>""")
        finally:
            fileobj.close()

        def template_loaded(template):
            def my_filter(stream, ctxt):
                for kind, data, pos in stream:
                    if kind is TEXT and data.strip():
                        data = ', '.join([data, data.lower()])
                    yield kind, data, pos
            template.filters.insert(0, my_filter)

        loader = TemplateLoader([self.dirname], callback=template_loaded)
        tmpl = loader.load('tmpl.html')
        self.assertEqual("""<html>
              <p>Hello, hello</p>
            </html>""", tmpl.generate().render())

        # Make sure the filter is only added once
        tmpl = loader.load('tmpl.html')
        self.assertEqual("""<html>
              <p>Hello, hello</p>
            </html>""", tmpl.generate().render())
Beispiel #4
0
    def test_abspath_caching(self):
        abspath = os.path.join(self.dirname, 'abs')
        os.mkdir(abspath)
        file1 = open(os.path.join(abspath, 'tmpl1.html'), 'w')
        try:
            file1.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="tmpl2.html" />
            </html>""")
        finally:
            file1.close()

        file2 = open(os.path.join(abspath, 'tmpl2.html'), 'w')
        try:
            file2.write("""<div>Included from abspath.</div>""")
        finally:
            file2.close()

        searchpath = os.path.join(self.dirname, 'searchpath')
        os.mkdir(searchpath)
        file3 = open(os.path.join(searchpath, 'tmpl2.html'), 'w')
        try:
            file3.write("""<div>Included from searchpath.</div>""")
        finally:
            file3.close()

        loader = TemplateLoader(searchpath)
        tmpl1 = loader.load(os.path.join(abspath, 'tmpl1.html'))
        self.assertEqual(
            """<html>
              <div>Included from searchpath.</div>
            </html>""",
            tmpl1.generate().render(encoding=None))
        assert 'tmpl2.html' in loader._cache
Beispiel #5
0
    def test_select_included_elements(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file1 = open(os.path.join(dirname, 'tmpl1.html'), 'w')
            try:
                file1.write("""<li>$item</li>""")
            finally:
                file1.close()

            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude"
                                     xmlns:py="http://genshi.edgewall.org/">
                  <ul py:match="ul">${select('li')}</ul>
                  <ul py:with="items=(1, 2, 3)">
                    <xi:include href="tmpl1.html" py:for="item in items" />
                  </ul>
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname])
            tmpl = loader.load('tmpl2.html')
            self.assertEqual("""<html>
                  <ul><li>1</li><li>2</li><li>3</li></ul>
                </html>""", tmpl.generate().render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Beispiel #6
0
    def test_include_inlined_in_loop(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file1 = open(os.path.join(dirname, 'tmpl1.html'), 'w')
            try:
                file1.write("""<div>Included $idx</div>""")
            finally:
                file1.close()

            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude"
                                     xmlns:py="http://genshi.edgewall.org/">
                  <xi:include href="tmpl1.html" py:for="idx in range(3)" />
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname], auto_reload=False)
            tmpl = loader.load('tmpl2.html')
            self.assertEqual("""<html>
                  <div>Included 0</div><div>Included 1</div><div>Included 2</div>
                </html>""", tmpl.generate().render(encoding=None))
        finally:
            shutil.rmtree(dirname)
    def test_include_inlined(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file1 = open(os.path.join(dirname, 'tmpl1.html'), 'w')
            try:
                file1.write("""<div>Included</div>""")
            finally:
                file1.close()

            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude"
                                     xmlns:py="http://genshi.edgewall.org/">
                  <xi:include href="tmpl1.html" />
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname], auto_reload=False)
            tmpl = loader.load('tmpl2.html')
            # if not inlined the following would be 5
            self.assertEqual(7, len(tmpl.stream))
            self.assertEqual("""<html>
                  <div>Included</div>
                </html>""", tmpl.generate().render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Beispiel #8
0
    def test_relative_include_samesubdir(self):
        file1 = open(os.path.join(self.dirname, 'tmpl1.html'), 'w')
        try:
            file1.write("""<div>Included tmpl1.html</div>""")
        finally:
            file1.close()

        os.mkdir(os.path.join(self.dirname, 'sub'))
        file2 = open(os.path.join(self.dirname, 'sub', 'tmpl1.html'), 'w')
        try:
            file2.write("""<div>Included sub/tmpl1.html</div>""")
        finally:
            file2.close()

        file3 = open(os.path.join(self.dirname, 'sub', 'tmpl2.html'), 'w')
        try:
            file3.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="tmpl1.html" />
            </html>""")
        finally:
            file3.close()

        loader = TemplateLoader([self.dirname])
        tmpl = loader.load('sub/tmpl2.html')
        self.assertEqual(
            """<html>
              <div>Included sub/tmpl1.html</div>
            </html>""",
            tmpl.generate().render())
Beispiel #9
0
    def test_include_inline_recursive(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file1 = open(os.path.join(dirname, 'tmpl1.html'), 'w')
            try:
                file1.write(
                    '<div xmlns:xi="http://www.w3.org/2001/XInclude"'
                    '                xmlns:py="http://genshi.edgewall.org/">'
                    '$depth'
                    '<py:with vars="depth = depth + 1">'
                    '<xi:include href="tmpl1.html"'
                    '            py:if="depth &lt; 3"/>'
                    '</py:with>'
                    '</div>'
                )
            finally:
                file1.close()

            loader = TemplateLoader([dirname], auto_reload=False)
            tmpl = loader.load(os.path.join(dirname, 'tmpl1.html'))
            self.assertEqual(
                "<div>0<div>1<div>2</div></div></div>",
                tmpl.generate(depth=0).render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Beispiel #10
0
    def test_abspath_caching(self):
        abspath = os.path.join(self.dirname, 'abs')
        os.mkdir(abspath)
        file1 = open(os.path.join(abspath, 'tmpl1.html'), 'w')
        try:
            file1.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="tmpl2.html" />
            </html>""")
        finally:
            file1.close()

        file2 = open(os.path.join(abspath, 'tmpl2.html'), 'w')
        try:
            file2.write("""<div>Included from abspath.</div>""")
        finally:
            file2.close()

        searchpath = os.path.join(self.dirname, 'searchpath')
        os.mkdir(searchpath)
        file3 = open(os.path.join(searchpath, 'tmpl2.html'), 'w')
        try:
            file3.write("""<div>Included from searchpath.</div>""")
        finally:
            file3.close()

        loader = TemplateLoader(searchpath)
        tmpl1 = loader.load(os.path.join(abspath, 'tmpl1.html'))
        self.assertEqual("""<html>
              <div>Included from searchpath.</div>
            </html>""", tmpl1.generate().render())
        assert 'tmpl2.html' in loader._cache
Beispiel #11
0
    def test_relative_absolute_template_preferred(self):
        file1 = open(os.path.join(self.dirname, 'tmpl1.html'), 'w')
        try:
            file1.write("""<div>Included</div>""")
        finally:
            file1.close()

        os.mkdir(os.path.join(self.dirname, 'sub'))
        file2 = open(os.path.join(self.dirname, 'sub', 'tmpl1.html'), 'w')
        try:
            file2.write("""<div>Included from sub</div>""")
        finally:
            file2.close()

        file3 = open(os.path.join(self.dirname, 'sub', 'tmpl2.html'), 'w')
        try:
            file3.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="tmpl1.html" />
            </html>""")
        finally:
            file3.close()

        loader = TemplateLoader()
        tmpl = loader.load(
            os.path.abspath(os.path.join(self.dirname, 'sub', 'tmpl2.html')))
        self.assertEqual(
            """<html>
              <div>Included from sub</div>
            </html>""",
            tmpl.generate().render(encoding=None))
Beispiel #12
0
    def test_dynamic_include_href(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file1 = open(os.path.join(dirname, 'tmpl1.html'), 'w')
            try:
                file1.write("""<div>Included</div>""")
            finally:
                file1.close()

            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude"
                                     xmlns:py="http://genshi.edgewall.org/">
                  <xi:include href="${name}.html" />
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname])
            tmpl = loader.load('tmpl2.html')
            self.assertEqual("""<html>
                  <div>Included</div>
                </html>""", tmpl.generate(name='tmpl1').render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Beispiel #13
0
    def test_relative_include_samesubdir(self):
        file1 = open(os.path.join(self.dirname, 'tmpl1.html'), 'w')
        try:
            file1.write("""<div>Included tmpl1.html</div>""")
        finally:
            file1.close()

        os.mkdir(os.path.join(self.dirname, 'sub'))
        file2 = open(os.path.join(self.dirname, 'sub', 'tmpl1.html'), 'w')
        try:
            file2.write("""<div>Included sub/tmpl1.html</div>""")
        finally:
            file2.close()

        file3 = open(os.path.join(self.dirname, 'sub', 'tmpl2.html'), 'w')
        try:
            file3.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="tmpl1.html" />
            </html>""")
        finally:
            file3.close()

        loader = TemplateLoader([self.dirname])
        tmpl = loader.load('sub/tmpl2.html')
        self.assertEqual("""<html>
              <div>Included sub/tmpl1.html</div>
            </html>""", tmpl.generate().render())
Beispiel #14
0
    def test_relative_include_without_search_path_nested(self):
        file1 = open(os.path.join(self.dirname, 'tmpl1.html'), 'w')
        try:
            file1.write("""<div>Included</div>""")
        finally:
            file1.close()

        file2 = open(os.path.join(self.dirname, 'tmpl2.html'), 'w')
        try:
            file2.write("""<div xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="tmpl1.html" />
            </div>""")
        finally:
            file2.close()

        file3 = open(os.path.join(self.dirname, 'tmpl3.html'), 'w')
        try:
            file3.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="tmpl2.html" />
            </html>""")
        finally:
            file3.close()

        loader = TemplateLoader()
        tmpl = loader.load(os.path.join(self.dirname, 'tmpl3.html'))
        self.assertEqual(
            """<html>
              <div>
              <div>Included</div>
            </div>
            </html>""",
            tmpl.generate().render(encoding=None))
Beispiel #15
0
    def test_include_inlined_in_loop(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file1 = open(os.path.join(dirname, 'tmpl1.html'), 'w')
            try:
                file1.write("""<div>Included $idx</div>""")
            finally:
                file1.close()

            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude"
                                     xmlns:py="http://genshi.edgewall.org/">
                  <xi:include href="tmpl1.html" py:for="idx in range(3)" />
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname], auto_reload=False)
            tmpl = loader.load('tmpl2.html')
            self.assertEqual("""<html>
                  <div>Included 0</div><div>Included 1</div><div>Included 2</div>
                </html>""", tmpl.generate().render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Beispiel #16
0
    def test_relative_include_without_search_path_nested(self):
        file1 = open(os.path.join(self.dirname, 'tmpl1.html'), 'w')
        try:
            file1.write("""<div>Included</div>""")
        finally:
            file1.close()

        file2 = open(os.path.join(self.dirname, 'tmpl2.html'), 'w')
        try:
            file2.write("""<div xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="tmpl1.html" />
            </div>""")
        finally:
            file2.close()

        file3 = open(os.path.join(self.dirname, 'tmpl3.html'), 'w')
        try:
            file3.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="tmpl2.html" />
            </html>""")
        finally:
            file3.close()

        loader = TemplateLoader()
        tmpl = loader.load(os.path.join(self.dirname, 'tmpl3.html'))
        self.assertEqual("""<html>
              <div>
              <div>Included</div>
            </div>
            </html>""", tmpl.generate().render())
Beispiel #17
0
    def test_include_expr(self):
        file1 = open(os.path.join(self.dirname, "tmpl1.txt"), "w")
        try:
            file1.write("Included")
        finally:
            file1.close()

        file2 = open(os.path.join(self.dirname, "tmpl2.txt"), "w")
        try:
            file2.write(
                """----- Included data below this line -----
    {% include ${'%s.txt' % ('tmpl1',)} %}
    ----- Included data above this line -----"""
            )
        finally:
            file2.close()

        loader = TemplateLoader([self.dirname])
        tmpl = loader.load("tmpl2.txt", cls=NewTextTemplate)
        self.assertEqual(
            """----- Included data below this line -----
    Included
    ----- Included data above this line -----""",
            tmpl.generate().render(encoding=None),
        )
Beispiel #18
0
    def test_relative_absolute_template_preferred(self):
        file1 = open(os.path.join(self.dirname, 'tmpl1.html'), 'w')
        try:
            file1.write("""<div>Included</div>""")
        finally:
            file1.close()

        os.mkdir(os.path.join(self.dirname, 'sub'))
        file2 = open(os.path.join(self.dirname, 'sub', 'tmpl1.html'), 'w')
        try:
            file2.write("""<div>Included from sub</div>""")
        finally:
            file2.close()

        file3 = open(os.path.join(self.dirname, 'sub', 'tmpl2.html'), 'w')
        try:
            file3.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="tmpl1.html" />
            </html>""")
        finally:
            file3.close()

        loader = TemplateLoader()
        tmpl = loader.load(os.path.abspath(os.path.join(self.dirname, 'sub',
                                                        'tmpl2.html')))
        self.assertEqual("""<html>
              <div>Included from sub</div>
            </html>""", tmpl.generate().render())
Beispiel #19
0
    def test_include_inline_recursive(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file1 = open(os.path.join(dirname, 'tmpl1.html'), 'w')
            try:
                file1.write(
                    '<div xmlns:xi="http://www.w3.org/2001/XInclude"'
                    '                xmlns:py="http://genshi.edgewall.org/">'
                    '$depth'
                    '<py:with vars="depth = depth + 1">'
                    '<xi:include href="tmpl1.html"'
                    '            py:if="depth &lt; 3"/>'
                    '</py:with>'
                    '</div>'
                )
            finally:
                file1.close()

            loader = TemplateLoader([dirname], auto_reload=False)
            tmpl = loader.load(os.path.join(dirname, 'tmpl1.html'))
            self.assertEqual(
                "<div>0<div>1<div>2</div></div></div>",
                tmpl.generate(depth=0).render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Beispiel #20
0
    def test_include_inlined(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file1 = open(os.path.join(dirname, 'tmpl1.html'), 'w')
            try:
                file1.write("""<div>Included</div>""")
            finally:
                file1.close()

            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude"
                                     xmlns:py="http://genshi.edgewall.org/">
                  <xi:include href="tmpl1.html" />
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname], auto_reload=False)
            tmpl = loader.load('tmpl2.html')
            # if not inlined the following would be 5
            self.assertEqual(7, len(tmpl.stream))
            self.assertEqual("""<html>
                  <div>Included</div>
                </html>""", tmpl.generate().render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Beispiel #21
0
    def test_select_included_elements(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file1 = open(os.path.join(dirname, 'tmpl1.html'), 'w')
            try:
                file1.write("""<li>$item</li>""")
            finally:
                file1.close()

            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude"
                                     xmlns:py="http://genshi.edgewall.org/">
                  <ul py:match="ul">${select('li')}</ul>
                  <ul py:with="items=(1, 2, 3)">
                    <xi:include href="tmpl1.html" py:for="item in items" />
                  </ul>
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname])
            tmpl = loader.load('tmpl2.html')
            self.assertEqual("""<html>
                  <ul><li>1</li><li>2</li><li>3</li></ul>
                </html>""", tmpl.generate().render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Beispiel #22
0
    def test_dynamic_include_href(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file1 = open(os.path.join(dirname, 'tmpl1.html'), 'w')
            try:
                file1.write("""<div>Included</div>""")
            finally:
                file1.close()

            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude"
                                     xmlns:py="http://genshi.edgewall.org/">
                  <xi:include href="${name}.html" />
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname])
            tmpl = loader.load('tmpl2.html')
            self.assertEqual("""<html>
                  <div>Included</div>
                </html>""", tmpl.generate(name='tmpl1').render(encoding=None))
        finally:
            shutil.rmtree(dirname)
    def filter_stream(self, req, method, filename, stream, data):
        if filename == 'browser.html' and req.method == 'GET':

            # we can only work from the 'dir' view at the moment
            if data.get('file'):
                return stream

            # TODO check that contextmenu's InternalNameHolder is enabled, as our js needs it?
            add_stylesheet(req, 'sourcesharer/filebox.css')
            add_javascript(req, 'sourcesharer/filebox.js')
            # Render the filebox template for stream insertion

            # TODO introduce a new interface to allow putting extra buttons into this filebox?
            tmpl = TemplateLoader(self.get_templates_dirs()).load('filebox.html')
            filebox = tmpl.generate(href=req.href, reponame=data['reponame'] or '', rev=data['rev'], files=[])
            # Wrap and float dirlist table, add filebox div
            # TODO change the id names, left/right seems a bit generic to assume we can have to ourselves
            stream |= Transformer('//table[@id="dirlist"]').wrap(tag.div(id="outer",style="clear:both")).wrap(tag.div(id="left"))
            stream |= Transformer('//div[@id="outer"]').append(tag.div(filebox, id="right"))

            is_svn_repo = False
            if 'repos' in data:
                is_svn_repo = isinstance(data.get('repos'), 
                                    (SvnCachedRepository, 
                                    SubversionRepository)) or False
            if is_svn_repo:
                add_ctxtnav(req, tag.a(_(tag.i(class_="fa fa-envelope-o")), " Send", href="", title=_("Send selected files"), id='share-files', class_='alt-button share-files-multiple'),
                    category='ctxtnav', order=10)

        return stream
Beispiel #24
0
    def test_nested_include_in_fallback(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file1 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file1.write("""<div>Included</div>""")
            finally:
                file1.close()

            file2 = open(os.path.join(dirname, 'tmpl3.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
                  <xi:include href="tmpl2.html">
                    <xi:fallback>
                      <xi:include href="tmpl1.html" />
                    </xi:fallback>
                  </xi:include>
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname])
            tmpl = loader.load('tmpl3.html')
            self.assertEqual("""<html>
                  <div>Included</div>
                </html>""", tmpl.generate().render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Beispiel #25
0
    def test_relative_include_parentdir(self):
        file1 = open(os.path.join(self.dirname, "tmpl1.html"), "w")
        try:
            file1.write("""<div>Included</div>""")
        finally:
            file1.close()

        os.mkdir(os.path.join(self.dirname, "sub"))
        file2 = open(os.path.join(self.dirname, "sub", "tmpl2.html"), "w")
        try:
            file2.write(
                """<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="../tmpl1.html" />
            </html>"""
            )
        finally:
            file2.close()

        loader = TemplateLoader([self.dirname])
        tmpl = loader.load("sub/tmpl2.html")
        self.assertEqual(
            """<html>
              <div>Included</div>
            </html>""",
            tmpl.generate().render(encoding=None),
        )
        def deco(*a, **b):
            """ Allow to get the docstring back"""
            try:
                ## Un-comment bellow for profiling each request:
                #import cherrypy.lib.profiler as profiler
                #p = profiler.Profiler("/Users/lia.domide/TVB/profiler/")
                #return p.run(profile, template_path, func, *a, **b)

                template_dict = func(*a, **b)
                if not cfg.RENDER_HTML:
                    return template_dict
                    ### Generate HTML given the path to the template and the data dictionary.
                loader = TemplateLoader()
                template = loader.load(template_path)
                stream = template.generate(**template_dict)
                return stream.render('xhtml')

            except Exception, excep:
                if isinstance(excep, cherrypy.HTTPRedirect):
                    raise excep
                get_logger("tvb.interface.web.controllers.basecontroller"
                           ).exception(excep)
                set_error_message(
                    "An unexpected exception appeared. Please contact your system administrator."
                )
                raise cherrypy.HTTPRedirect("/tvb?error=True")
Beispiel #27
0
 def test_load_with_explicit_encoding(self):
     f = open(os.path.join(self.dirname, 'tmpl.html'), 'w')
     try:
         f.write(u'<div>\xf6</div>'.encode('iso-8859-1'))
     finally:
         f.close()
     loader = TemplateLoader([self.dirname], default_encoding='utf-8')
     loader.load('tmpl.html', encoding='iso-8859-1')
Beispiel #28
0
 def __init__(self):
     self.paths = [
         os.path.join(d, 'templates') for d in [
             config.server_dir,
             pkg_resources.resource_filename('webias', 'data')
         ]
     ]
     self.templateLoader = TemplateLoader(self.paths, auto_reload=True)
Beispiel #29
0
 def test_load_with_explicit_encoding(self):
     f = open(os.path.join(self.dirname, "tmpl.html"), "wb")
     try:
         f.write(u"<div>\xf6</div>".encode("iso-8859-1"))
     finally:
         f.close()
     loader = TemplateLoader([self.dirname], default_encoding="utf-8")
     loader.load("tmpl.html", encoding="iso-8859-1")
Beispiel #30
0
 def test_load_with_explicit_encoding(self):
     f = open(os.path.join(self.dirname, 'tmpl.html'), 'w')
     try:
         f.write(u'<div>\xf6</div>'.encode('iso-8859-1'))
     finally:
         f.close()
     loader = TemplateLoader([self.dirname], default_encoding='utf-8')
     loader.load('tmpl.html', encoding='iso-8859-1')
Beispiel #31
0
    def test_prefix_delegation_to_directories_with_subdirs(self):
        """
        Test prefix delegation with the following layout:
        
        templates/foo.html
        sub1/templates/tmpl1.html
        sub1/templates/tmpl2.html
        sub1/templates/bar/tmpl3.html
        
        Where sub1 is a prefix, and tmpl1.html includes all the others.
        """
        dir1 = os.path.join(self.dirname, 'templates')
        os.mkdir(dir1)
        file1 = open(os.path.join(dir1, 'foo.html'), 'w')
        try:
            file1.write("""<div>Included foo</div>""")
        finally:
            file1.close()

        dir2 = os.path.join(self.dirname, 'sub1', 'templates')
        os.makedirs(dir2)
        file2 = open(os.path.join(dir2, 'tmpl1.html'), 'w')
        try:
            file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="../foo.html" /> from sub1
              <xi:include href="tmpl2.html" /> from sub1
              <xi:include href="bar/tmpl3.html" /> from sub1
            </html>""")
        finally:
            file2.close()

        file3 = open(os.path.join(dir2, 'tmpl2.html'), 'w')
        try:
            file3.write("""<div>tmpl2</div>""")
        finally:
            file3.close()

        dir3 = os.path.join(self.dirname, 'sub1', 'templates', 'bar')
        os.makedirs(dir3)
        file4 = open(os.path.join(dir3, 'tmpl3.html'), 'w')
        try:
            file4.write("""<div>bar/tmpl3</div>""")
        finally:
            file4.close()

        loader = TemplateLoader([
            dir1,
            TemplateLoader.prefixed(sub1=os.path.join(dir2),
                                    sub2=os.path.join(dir3))
        ])
        tmpl = loader.load('sub1/tmpl1.html')
        self.assertEqual(
            """<html>
              <div>Included foo</div> from sub1
              <div>tmpl2</div> from sub1
              <div>bar/tmpl3</div> from sub1
            </html>""",
            tmpl.generate().render(encoding=None))
Beispiel #32
0
    def test_prefix_delegation_to_directories_with_subdirs(self):
        """
        Test prefix delegation with the following layout:
        
        templates/foo.html
        sub1/templates/tmpl1.html
        sub1/templates/tmpl2.html
        sub1/templates/bar/tmpl3.html
        
        Where sub1 is a prefix, and tmpl1.html includes all the others.
        """
        dir1 = os.path.join(self.dirname, "templates")
        os.mkdir(dir1)
        file1 = open(os.path.join(dir1, "foo.html"), "w")
        try:
            file1.write("""<div>Included foo</div>""")
        finally:
            file1.close()

        dir2 = os.path.join(self.dirname, "sub1", "templates")
        os.makedirs(dir2)
        file2 = open(os.path.join(dir2, "tmpl1.html"), "w")
        try:
            file2.write(
                """<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="../foo.html" /> from sub1
              <xi:include href="tmpl2.html" /> from sub1
              <xi:include href="bar/tmpl3.html" /> from sub1
            </html>"""
            )
        finally:
            file2.close()

        file3 = open(os.path.join(dir2, "tmpl2.html"), "w")
        try:
            file3.write("""<div>tmpl2</div>""")
        finally:
            file3.close()

        dir3 = os.path.join(self.dirname, "sub1", "templates", "bar")
        os.makedirs(dir3)
        file4 = open(os.path.join(dir3, "tmpl3.html"), "w")
        try:
            file4.write("""<div>bar/tmpl3</div>""")
        finally:
            file4.close()

        loader = TemplateLoader([dir1, TemplateLoader.prefixed(sub1=os.path.join(dir2), sub2=os.path.join(dir3))])
        tmpl = loader.load("sub1/tmpl1.html")
        self.assertEqual(
            """<html>
              <div>Included foo</div> from sub1
              <div>tmpl2</div> from sub1
              <div>bar/tmpl3</div> from sub1
            </html>""",
            tmpl.generate().render(encoding=None),
        )
Beispiel #33
0
    def test_nested_include_matches(self):
        # See ticket #157
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file1 = open(os.path.join(dirname, 'tmpl1.html'), 'w')
            try:
                file1.write(
                    """<html xmlns:py="http://genshi.edgewall.org/" py:strip="">
   <div class="target">Some content.</div>
</html>""")
            finally:
                file1.close()

            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:py="http://genshi.edgewall.org/"
    xmlns:xi="http://www.w3.org/2001/XInclude">
  <body>
    <h1>Some full html document that includes file1.html</h1>
    <xi:include href="tmpl1.html" />
  </body>
</html>""")
            finally:
                file2.close()

            file3 = open(os.path.join(dirname, 'tmpl3.html'), 'w')
            try:
                file3.write("""<html xmlns:py="http://genshi.edgewall.org/"
    xmlns:xi="http://www.w3.org/2001/XInclude" py:strip="">
  <div py:match="div[@class='target']" py:attrs="select('@*')">
    Some added stuff.
    ${select('*|text()')}
  </div>
  <xi:include href="tmpl2.html" />
</html>
""")
            finally:
                file3.close()

            loader = TemplateLoader([dirname])
            tmpl = loader.load('tmpl3.html')
            self.assertEqual(
                """
  <html>
  <body>
    <h1>Some full html document that includes file1.html</h1>
   <div class="target">
    Some added stuff.
    Some content.
  </div>
  </body>
</html>
""",
                tmpl.generate().render(encoding=None))
        finally:
            shutil.rmtree(dirname)
def _template2string(template_specification):
    """
    Here we use the TemplateLoader from Genshi, so we are linked to this library for comparison.
    """
    template_specification[common.KEY_SHOW_ONLINE_HELP] = False
    path_to_form = os.path.join(os.path.dirname(root_html.__file__), 'genericAdapterFormFields.html')
    loader = TemplateLoader()
    template = loader.load(path_to_form)
    stream = template.generate(**template_specification)
    return stream.render('xhtml').replace('\n', '\t').replace('\'', '"')
def _template2string(template_specification):
    """
    Here we use the TemplateLoader from Genshi, so we are linked to this library for comparison.
    """
    template_specification[common.KEY_SHOW_ONLINE_HELP] = False
    path_to_form = os.path.join(os.path.dirname(root_html.__file__), 'genericAdapterFormFields.html')
    loader = TemplateLoader()
    template = loader.load(path_to_form)
    stream = template.generate(**template_specification)
    return stream.render('xhtml').replace('\n', '\t').replace('\'', '"')
def profile(template_path, func, *a, **b):
    """
    Wrapping function, used when profiling.
    We duplicate the code here, in a separate function, to help profiling,
    but for the runtime process we do not want a separate call, to increase time.
    """
    template_dict = func(*a, **b)
    ### Generate HTML given the path to the template and the data dictionary.
    loader = TemplateLoader()
    template = loader.load(template_path)
    stream = template.generate(**template_dict)
    return stream.render('xhtml')
def profile(template_path, func, *a, **b):
    """
    Wrapping function, used when profiling.
    We duplicate the code here, in a separate function, to help profiling,
    but for the runtime process we do not want a separate call, to increase time.
    """
    template_dict = func(*a, **b)
    ### Generate HTML given the path to the template and the data dictionary.
    loader = TemplateLoader()
    template = loader.load(template_path)
    stream = template.generate(**template_dict)
    return stream.render('xhtml')
Beispiel #38
0
 def _init_loader(self):
     if self.loader is None:
         from genshi.template.loader import TemplateLoader
         if self.filename:
             if self.filepath != self.filename:
                 basedir = os.path.normpath(
                     self.filepath)[:-len(os.path.normpath(self.filename))]
             else:
                 basedir = os.path.dirname(self.filename)
         else:
             basedir = '.'
         self.loader = TemplateLoader([os.path.abspath(basedir)])
Beispiel #39
0
    def test_nested_include_matches(self):
        # See ticket #157
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file1 = open(os.path.join(dirname, 'tmpl1.html'), 'w')
            try:
                file1.write("""<html xmlns:py="http://genshi.edgewall.org/" py:strip="">
   <div class="target">Some content.</div>
</html>""")
            finally:
                file1.close()

            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:py="http://genshi.edgewall.org/"
    xmlns:xi="http://www.w3.org/2001/XInclude">
  <body>
    <h1>Some full html document that includes file1.html</h1>
    <xi:include href="tmpl1.html" />
  </body>
</html>""")
            finally:
                file2.close()

            file3 = open(os.path.join(dirname, 'tmpl3.html'), 'w')
            try:
                file3.write("""<html xmlns:py="http://genshi.edgewall.org/"
    xmlns:xi="http://www.w3.org/2001/XInclude" py:strip="">
  <div py:match="div[@class='target']" py:attrs="select('@*')">
    Some added stuff.
    ${select('*|text()')}
  </div>
  <xi:include href="tmpl2.html" />
</html>
""")
            finally:
                file3.close()

            loader = TemplateLoader([dirname])
            tmpl = loader.load('tmpl3.html')
            self.assertEqual("""
  <html>
  <body>
    <h1>Some full html document that includes file1.html</h1>
   <div class="target">
    Some added stuff.
    Some content.
  </div>
  </body>
</html>
""", tmpl.generate().render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Beispiel #40
0
def generate_appearance_css(settings, cache_dir=None):
    """Generate the custom appearance.css file, overwriting if it exists.

    :param settings: A list of settings key-value tuples.
    :param cache_dir: Path to the data directory. Optional if the
        ``pylons.config`` Stacked Object Proxy is available (ie.
        during the life of a request, but not during websetup or init).
    :raises TypeError: If cache_dir is not provided and cannot be found.
    :raises ValueError: If the cache_dir does not exist.

    """
    if cache_dir is None:
        cache_dir = pylons.config['pylons.cache_dir']
    if not os.path.exists(cache_dir):
        raise ValueError('No valid cache dir provided.')

    appearance_dir = os.path.join(cache_dir, 'appearance')
    css_path = os.path.join(appearance_dir, 'appearance.css')

    vars = dict((k.encode('utf-8'), v.encode('utf-8'))
                for k, v in settings
                if k.startswith('appearance_'))
    vars['uikit_colors'] = uikit_colors[
        vars['appearance_navigation_bar_color']]
    vars['navbar_color'] = vars['appearance_navigation_bar_color']

    if vars['appearance_logo']:
        logo_path = os.path.join(appearance_dir, vars['appearance_logo'])
        if os.path.exists(logo_path):
            vars['logo_height'] = Image.open(logo_path).size[1]
            vars['logo_name'] = vars['appearance_logo']
        else:
            vars['appearance_logo'] = False

    # Create a simple template loader instead of using
    # mediadrop.lib.templating.render because that function only works
    # within the context of a request, when the pylons magic globals
    # have been populated.
    tmpl_loader = TemplateLoader([os.path.join(here, 'templates')])
    tmpl = tmpl_loader.load('appearance.css', cls=NewTextTemplate)
    css = tmpl.generate(**vars).render('text')

    warning = ('/*\n'
               ' * This file is automatically generated by MediaDrop.\n'
               ' * Please do not edit this file directly.\n'
               ' */\n\n')

    css_file = open(css_path, 'w')
    css_file.write(warning + css)
    css_file.close()
Beispiel #41
0
    def test_abspath_include_caching_without_search_path(self):
        file1 = open(os.path.join(self.dirname, "tmpl1.html"), "w")
        try:
            file1.write(
                """<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="tmpl2.html" />
            </html>"""
            )
        finally:
            file1.close()

        file2 = open(os.path.join(self.dirname, "tmpl2.html"), "w")
        try:
            file2.write("""<div>Included</div>""")
        finally:
            file2.close()

        os.mkdir(os.path.join(self.dirname, "sub"))
        file3 = open(os.path.join(self.dirname, "sub", "tmpl1.html"), "w")
        try:
            file3.write(
                """<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="tmpl2.html" />
            </html>"""
            )
        finally:
            file3.close()

        file4 = open(os.path.join(self.dirname, "sub", "tmpl2.html"), "w")
        try:
            file4.write("""<div>Included from sub</div>""")
        finally:
            file4.close()

        loader = TemplateLoader()
        tmpl1 = loader.load(os.path.join(self.dirname, "tmpl1.html"))
        self.assertEqual(
            """<html>
              <div>Included</div>
            </html>""",
            tmpl1.generate().render(encoding=None),
        )
        tmpl2 = loader.load(os.path.join(self.dirname, "sub", "tmpl1.html"))
        self.assertEqual(
            """<html>
              <div>Included from sub</div>
            </html>""",
            tmpl2.generate().render(encoding=None),
        )
        assert "tmpl2.html" not in loader._cache
Beispiel #42
0
def generate_appearance_css(settings, cache_dir=None):
    """Generate the custom appearance.css file, overwriting if it exists.

    :param settings: A list of settings key-value tuples.
    :param cache_dir: Path to the data directory. Optional if the
        ``pylons.config`` Stacked Object Proxy is available (ie.
        during the life of a request, but not during websetup or init).
    :raises TypeError: If cache_dir is not provided and cannot be found.
    :raises ValueError: If the cache_dir does not exist.

    """
    if cache_dir is None:
        cache_dir = pylons.config['pylons.cache_dir']
    if not os.path.exists(cache_dir):
        raise ValueError('No valid cache dir provided.')

    appearance_dir = os.path.join(cache_dir, 'appearance')
    css_path = os.path.join(appearance_dir, 'appearance.css')

    vars = dict((k.encode('utf-8'), v.encode('utf-8'))
                for k, v in settings
                if k.startswith('appearance_'))
    vars['uikit_colors'] = uikit_colors[
        vars['appearance_navigation_bar_color']]
    vars['navbar_color'] = vars['appearance_navigation_bar_color']

    if vars['appearance_logo']:
        logo_path = os.path.join(appearance_dir, vars['appearance_logo'])
        if os.path.exists(logo_path):
            vars['logo_height'] = Image.open(logo_path).size[1]
            vars['logo_name'] = vars['appearance_logo']
        else:
            vars['appearance_logo'] = False

    # Create a simple template loader instead of using
    # mediadrop.lib.templating.render because that function only works
    # within the context of a request, when the pylons magic globals
    # have been populated.
    tmpl_loader = TemplateLoader([os.path.join(here, 'templates')])
    tmpl = tmpl_loader.load('appearance.css', cls=NewTextTemplate)
    css = tmpl.generate(**vars).render('text')

    warning = ('/*\n'
               ' * This file is automatically generated by MediaDrop.\n'
               ' * Please do not edit this file directly.\n'
               ' */\n\n')

    css_file = open(css_path, 'w')
    css_file.write(warning + css)
    css_file.close()
Beispiel #43
0
class GenshiRenderer(object):
    def __init__(self, *a, **k):
        self.loader = TemplateLoader(*a, **k)

    def __call__(self, template, args={}, encoding=None):
        return self.loader.load(template).generate(**args).render(
            encoding=encoding)
Beispiel #44
0
    def _load_template_snippet(self, filename, data=None):
        """ Load a genshi template snippet from a file then apply the snippet
        to any supplied context data.

        :param filename: the name of the file containing the template snippet
        :param data: a dictionary of data to which the loaded template snippet
            may be applied

        The returned object is a Genshi Markup event stream, containing the
        HTML generated by applying the template snippet to any supplied context
        data.

        """
        loader = TemplateLoader(search_path=resource_filename(__name__, 'templates'))
        template = loader.load(filename)
        return template.generate(data=data)
Beispiel #45
0
    def test_error_when_include_not_found(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
                  <xi:include href="tmpl1.html"/>
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname], auto_reload=True)
            tmpl = loader.load('tmpl2.html')
            self.assertRaises(TemplateNotFound, tmpl.generate().render)
        finally:
            shutil.rmtree(dirname)
Beispiel #46
0
    def test_error_when_include_not_found(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
                  <xi:include href="tmpl1.html"/>
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname], auto_reload=True)
            tmpl = loader.load('tmpl2.html')
            self.assertRaises(TemplateNotFound, tmpl.generate().render)
        finally:
            shutil.rmtree(dirname)
Beispiel #47
0
class GenshiRenderer(object):

    def __init__(self, *a, **k):
        self.loader = TemplateLoader(*a, **k)

    def __call__(self, template, args={}, encoding=None):
        return self.loader.load(template).generate(**args).render(encoding=encoding)
Beispiel #48
0
    def test_prefix_delegation_to_directories(self):
        """
        Test prefix delegation with the following layout:
        
        templates/foo.html
        sub1/templates/tmpl1.html
        sub2/templates/tmpl2.html
        
        Where sub1 and sub2 are prefixes, and both tmpl1.html and tmpl2.html
        incldue foo.html.
        """
        dir1 = os.path.join(self.dirname, 'templates')
        os.mkdir(dir1)
        file1 = open(os.path.join(dir1, 'foo.html'), 'w')
        try:
            file1.write("""<div>Included foo</div>""")
        finally:
            file1.close()

        dir2 = os.path.join(self.dirname, 'sub1', 'templates')
        os.makedirs(dir2)
        file2 = open(os.path.join(dir2, 'tmpl1.html'), 'w')
        try:
            file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="../foo.html" /> from sub1
            </html>""")
        finally:
            file2.close()

        dir3 = os.path.join(self.dirname, 'sub2', 'templates')
        os.makedirs(dir3)
        file3 = open(os.path.join(dir3, 'tmpl2.html'), 'w')
        try:
            file3.write("""<div>tmpl2</div>""")
        finally:
            file3.close()

        loader = TemplateLoader([dir1, TemplateLoader.prefixed(
            sub1 = dir2,
            sub2 = dir3
        )])
        tmpl = loader.load('sub1/tmpl1.html')
        self.assertEqual("""<html>
              <div>Included foo</div> from sub1
            </html>""", tmpl.generate().render())
Beispiel #49
0
    def test_abspath_include_caching_without_search_path(self):
        file1 = open(os.path.join(self.dirname, 'tmpl1.html'), 'w')
        try:
            file1.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="tmpl2.html" />
            </html>""")
        finally:
            file1.close()

        file2 = open(os.path.join(self.dirname, 'tmpl2.html'), 'w')
        try:
            file2.write("""<div>Included</div>""")
        finally:
            file2.close()

        os.mkdir(os.path.join(self.dirname, 'sub'))
        file3 = open(os.path.join(self.dirname, 'sub', 'tmpl1.html'), 'w')
        try:
            file3.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="tmpl2.html" />
            </html>""")
        finally:
            file3.close()

        file4 = open(os.path.join(self.dirname, 'sub', 'tmpl2.html'), 'w')
        try:
            file4.write("""<div>Included from sub</div>""")
        finally:
            file4.close()

        loader = TemplateLoader()
        tmpl1 = loader.load(os.path.join(self.dirname, 'tmpl1.html'))
        self.assertEqual(
            """<html>
              <div>Included</div>
            </html>""",
            tmpl1.generate().render(encoding=None))
        tmpl2 = loader.load(os.path.join(self.dirname, 'sub', 'tmpl1.html'))
        self.assertEqual(
            """<html>
              <div>Included from sub</div>
            </html>""",
            tmpl2.generate().render(encoding=None))
        assert 'tmpl2.html' not in loader._cache
Beispiel #50
0
    def test_fallback_when_auto_reload_true(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
                  <xi:include href="tmpl1.html"><xi:fallback>
                    Missing</xi:fallback></xi:include>
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname], auto_reload=True)
            tmpl = loader.load('tmpl2.html')
            self.assertEqual("""<html>
                    Missing
                </html>""", tmpl.generate().render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Beispiel #51
0
    def test_fallback_when_auto_reload_true(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
                  <xi:include href="tmpl1.html"><xi:fallback>
                    Missing</xi:fallback></xi:include>
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname], auto_reload=True)
            tmpl = loader.load('tmpl2.html')
            self.assertEqual("""<html>
                    Missing
                </html>""", tmpl.generate().render(encoding=None))
        finally:
            shutil.rmtree(dirname)
    def __init__(self, extra_vars_func=None, options=None):
        self.get_extra_vars = extra_vars_func
        if options is None:
            options = {}
        self.options = options

        self.default_encoding = options.get('genshi.default_encoding', None)
        auto_reload = options.get('genshi.auto_reload', '1')
        if isinstance(auto_reload, str):
            auto_reload = auto_reload.lower() in ('1', 'on', 'yes', 'true')
        search_path = [
            p for p in options.get('genshi.search_path', '').split(':') if p
        ]
        self.use_package_naming = not search_path
        try:
            max_cache_size = int(options.get('genshi.max_cache_size', 25))
        except ValueError:
            raise ConfigurationError('Invalid value for max_cache_size: "%s"' %
                                     options.get('genshi.max_cache_size'))

        loader_callback = options.get('genshi.loader_callback', None)
        if loader_callback and not hasattr(loader_callback, '__call__'):
            raise ConfigurationError('loader callback must be a function')

        lookup_errors = options.get('genshi.lookup_errors', 'strict')
        if lookup_errors not in ('lenient', 'strict'):
            raise ConfigurationError('Unknown lookup errors mode "%s"' %
                                     lookup_errors)

        try:
            allow_exec = bool(options.get('genshi.allow_exec', True))
        except ValueError:
            raise ConfigurationError('Invalid value for allow_exec "%s"' %
                                     options.get('genshi.allow_exec'))

        self.loader = TemplateLoader([p for p in search_path if p],
                                     auto_reload=auto_reload,
                                     max_cache_size=max_cache_size,
                                     default_class=self.template_class,
                                     variable_lookup=lookup_errors,
                                     allow_exec=allow_exec,
                                     callback=loader_callback)
Beispiel #53
0
    def test_include(self):
        file1 = open(os.path.join(self.dirname, 'tmpl1.txt'), 'w')
        try:
            file1.write("Included")
        finally:
            file1.close()

        file2 = open(os.path.join(self.dirname, 'tmpl2.txt'), 'w')
        try:
            file2.write("""----- Included data below this line -----
{% include tmpl1.txt %}
----- Included data above this line -----""")
        finally:
            file2.close()

        loader = TemplateLoader([self.dirname])
        tmpl = loader.load('tmpl2.txt', cls=NewTextTemplate)
        self.assertEqual("""----- Included data below this line -----
Included
----- Included data above this line -----""", tmpl.generate().render())
Beispiel #54
0
    def test_include_fallback_with_directive(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude"
                      xmlns:py="http://genshi.edgewall.org/">
                  <xi:include href="tmpl1.html"><xi:fallback>
                    <py:if test="True">tmpl1.html not found</py:if>
                  </xi:fallback></xi:include>
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname])
            tmpl = loader.load('tmpl2.html')
            self.assertEqual("""<html>
                    tmpl1.html not found
                </html>""", tmpl.generate(debug=True).render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Beispiel #55
0
    def test_include(self):
        file1 = open(os.path.join(self.dirname, 'tmpl1.txt'), 'wb')
        try:
            file1.write(u"Included\n".encode("utf-8"))
        finally:
            file1.close()

        file2 = open(os.path.join(self.dirname, 'tmpl2.txt'), 'wb')
        try:
            file2.write(u"""----- Included data below this line -----
            #include tmpl1.txt
            ----- Included data above this line -----""".encode("utf-8"))
        finally:
            file2.close()

        loader = TemplateLoader([self.dirname])
        tmpl = loader.load('tmpl2.txt', cls=OldTextTemplate)
        self.assertEqual("""----- Included data below this line -----
Included
            ----- Included data above this line -----""",
                         tmpl.generate().render(encoding=None))
Beispiel #56
0
    def test_include_fallback_with_directive(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude"
                      xmlns:py="http://genshi.edgewall.org/">
                  <xi:include href="tmpl1.html"><xi:fallback>
                    <py:if test="True">tmpl1.html not found</py:if>
                  </xi:fallback></xi:include>
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname])
            tmpl = loader.load('tmpl2.html')
            self.assertEqual("""<html>
                    tmpl1.html not found
                </html>""", tmpl.generate(debug=True).render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Beispiel #57
0
    def test_include_expr(self):
        file1 = open(os.path.join(self.dirname, 'tmpl1.txt'), 'wb')
        try:
            file1.write(u"Included".encode("utf-8"))
        finally:
            file1.close()

        file2 = open(os.path.join(self.dirname, 'tmpl2.txt'), 'wb')
        try:
            file2.write(u"""----- Included data below this line -----
    {% include ${'%s.txt' % ('tmpl1',)} %}
    ----- Included data above this line -----""".encode("utf-8"))
        finally:
            file2.close()

        loader = TemplateLoader([self.dirname])
        tmpl = loader.load('tmpl2.txt', cls=NewTextTemplate)
        self.assertEqual(
            """----- Included data below this line -----
    Included
    ----- Included data above this line -----""",
            tmpl.generate().render(encoding=None))
Beispiel #58
0
    def test_include(self):
        file1 = open(os.path.join(self.dirname, 'tmpl1.txt'), 'w')
        try:
            file1.write("Included\n")
        finally:
            file1.close()

        file2 = open(os.path.join(self.dirname, 'tmpl2.txt'), 'w')
        try:
            file2.write("""----- Included data below this line -----
            #include tmpl1.txt
            ----- Included data above this line -----""")
        finally:
            file2.close()

        loader = TemplateLoader([self.dirname])
        tmpl = loader.load('tmpl2.txt', cls=OldTextTemplate)
        self.assertEqual(
            """----- Included data below this line -----
Included
            ----- Included data above this line -----""",
            tmpl.generate().render())
    def test_relative_include_from_inmemory_template(self):
        file1 = open(os.path.join(self.dirname, 'tmpl1.html'), 'w')
        try:
            file1.write("""<div>Included</div>""")
        finally:
            file1.close()

        loader = TemplateLoader([self.dirname])
        tmpl2 = MarkupTemplate("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
          <xi:include href="../tmpl1.html" />
        </html>""", filename='subdir/tmpl2.html', loader=loader)

        self.assertEqual("""<html>
          <div>Included</div>
        </html>""", tmpl2.generate().render(encoding=None))
Beispiel #60
0
class Template(DirectiveFactory):
    """Abstract template base class.
    
    This class implements most of the template processing model, but does not
    specify the syntax of templates.
    """

    EXEC = StreamEventKind('EXEC')
    """Stream event kind representing a Python code suite to execute."""

    EXPR = StreamEventKind('EXPR')
    """Stream event kind representing a Python expression."""

    INCLUDE = StreamEventKind('INCLUDE')
    """Stream event kind representing the inclusion of another template."""

    SUB = StreamEventKind('SUB')
    """Stream event kind representing a nested stream to which one or more
    directives should be applied.
    """

    serializer = None
    _number_conv = str  # function used to convert numbers to event data

    def __init__(self,
                 source,
                 filepath=None,
                 filename=None,
                 loader=None,
                 encoding=None,
                 lookup='strict',
                 allow_exec=True):
        """Initialize a template from either a string, a file-like object, or
        an already parsed markup stream.
        
        :param source: a string, file-like object, or markup stream to read the
                       template from
        :param filepath: the absolute path to the template file
        :param filename: the path to the template file relative to the search
                         path
        :param loader: the `TemplateLoader` to use for loading included
                       templates
        :param encoding: the encoding of the `source`
        :param lookup: the variable lookup mechanism; either "strict" (the
                       default), "lenient", or a custom lookup class
        :param allow_exec: whether Python code blocks in templates should be
                           allowed
        
        :note: Changed in 0.5: Added the `allow_exec` argument
        """
        self.filepath = filepath or filename
        self.filename = filename
        self.loader = loader
        self.lookup = lookup
        self.allow_exec = allow_exec
        self._init_filters()
        self._init_loader()
        self._prepared = False

        if not isinstance(source, Stream) and not hasattr(source, 'read'):
            if isinstance(source, str):
                source = StringIO(source)
            else:
                source = BytesIO(source)
        try:
            self._stream = self._parse(source, encoding)
        except ParseError as e:
            raise TemplateSyntaxError(e.msg, self.filepath, e.lineno, e.offset)

    def __getstate__(self):
        state = self.__dict__.copy()
        state['filters'] = []
        return state

    def __setstate__(self, state):
        self.__dict__ = state
        self._init_filters()

    def __repr__(self):
        return '<%s "%s">' % (type(self).__name__, self.filename)

    def _init_filters(self):
        self.filters = [self._flatten, self._include]

    def _init_loader(self):
        if self.loader is None:
            from genshi.template.loader import TemplateLoader
            if self.filename:
                if self.filepath != self.filename:
                    basedir = os.path.normpath(
                        self.filepath)[:-len(os.path.normpath(self.filename))]
                else:
                    basedir = os.path.dirname(self.filename)
            else:
                basedir = '.'
            self.loader = TemplateLoader([os.path.abspath(basedir)])

    @property
    def stream(self):
        if not self._prepared:
            self._prepare_self()
        return self._stream

    def _parse(self, source, encoding):
        """Parse the template.
        
        The parsing stage parses the template and constructs a list of
        directives that will be executed in the render stage. The input is
        split up into literal output (text that does not depend on the context
        data) and directives or expressions.
        
        :param source: a file-like object containing the XML source of the
                       template, or an XML event stream
        :param encoding: the encoding of the `source`
        """
        raise NotImplementedError

    def _prepare_self(self, inlined=None):
        if not self._prepared:
            self._stream = list(self._prepare(self._stream, inlined))
            self._prepared = True

    def _prepare(self, stream, inlined):
        """Call the `attach` method of every directive found in the template.
        
        :param stream: the event stream of the template
        """
        from genshi.template.loader import TemplateNotFound
        if inlined is None:
            inlined = set((self.filepath, ))

        for kind, data, pos in stream:
            if kind is SUB:
                directives = []
                substream = data[1]
                for _, cls, value, namespaces, pos in sorted(data[0]):
                    directive, substream = cls.attach(self, substream, value,
                                                      namespaces, pos)
                    if directive:
                        directives.append(directive)
                substream = self._prepare(substream, inlined)
                if directives:
                    yield kind, (directives, list(substream)), pos
                else:
                    for event in substream:
                        yield event
            else:
                if kind is INCLUDE:
                    href, cls, fallback = data
                    tmpl_inlined = False
                    if (isinstance(href, str)
                            and not getattr(self.loader, 'auto_reload', True)):
                        # If the path to the included template is static, and
                        # auto-reloading is disabled on the template loader,
                        # the template is inlined into the stream provided it
                        # is not already in the stack of templates being
                        # processed.
                        tmpl = None
                        try:
                            tmpl = self.loader.load(href,
                                                    relative_to=pos[0],
                                                    cls=cls or self.__class__)
                        except TemplateNotFound:
                            if fallback is None:
                                raise
                        if tmpl is not None:
                            if tmpl.filepath not in inlined:
                                inlined.add(tmpl.filepath)
                                tmpl._prepare_self(inlined)
                                for event in tmpl.stream:
                                    yield event
                                inlined.discard(tmpl.filepath)
                                tmpl_inlined = True
                        else:
                            for event in self._prepare(fallback, inlined):
                                yield event
                            tmpl_inlined = True
                    if tmpl_inlined:
                        continue
                    if fallback:
                        # Otherwise the include is performed at run time
                        data = href, cls, list(self._prepare(
                            fallback, inlined))
                    yield kind, data, pos
                else:
                    yield kind, data, pos

    def generate(self, *args, **kwargs):
        """Apply the template to the given context data.
        
        Any keyword arguments are made available to the template as context
        data.
        
        Only one positional argument is accepted: if it is provided, it must be
        an instance of the `Context` class, and keyword arguments are ignored.
        This calling style is used for internal processing.
        
        :return: a markup event stream representing the result of applying
                 the template to the context data.
        """
        vars = {}
        if args:
            assert len(args) == 1
            ctxt = args[0]
            if ctxt is None:
                ctxt = Context(**kwargs)
            else:
                vars = kwargs
            assert isinstance(ctxt, Context)
        else:
            ctxt = Context(**kwargs)

        stream = self.stream
        for filter_ in self.filters:
            stream = filter_(iter(stream), ctxt, **vars)
        return Stream(stream, self.serializer)

    def _flatten(self, stream, ctxt, **vars):
        number_conv = self._number_conv
        stack = []
        push = stack.append
        pop = stack.pop
        stream = iter(stream)

        while 1:
            for kind, data, pos in stream:

                if kind is START and data[1]:
                    # Attributes may still contain expressions in start tags at
                    # this point, so do some evaluation
                    tag, attrs = data
                    new_attrs = []
                    for name, value in attrs:
                        if type(value
                                ) is list:  # this is an interpolated string
                            values = [
                                event[1] for event in self._flatten(
                                    value, ctxt, **vars)
                                if event[0] is TEXT and event[1] is not None
                            ]
                            if not values:
                                continue
                            value = ''.join(values)
                        new_attrs.append((name, value))
                    yield kind, (tag, Attrs(new_attrs)), pos

                elif kind is EXPR:
                    result = _eval_expr(data, ctxt, vars)
                    if result is not None:
                        # First check for a string, otherwise the iterable test
                        # below succeeds, and the string will be chopped up into
                        # individual characters
                        if isinstance(result, str):
                            yield TEXT, result, pos
                        elif isinstance(result, (int, float)):
                            yield TEXT, number_conv(result), pos
                        elif hasattr(result, '__iter__'):
                            push(stream)
                            stream = _ensure(result)
                            break
                        else:
                            yield TEXT, str(result), pos

                elif kind is SUB:
                    # This event is a list of directives and a list of nested
                    # events to which those directives should be applied
                    push(stream)
                    stream = _apply_directives(data[1], data[0], ctxt, vars)
                    break

                elif kind is EXEC:
                    _exec_suite(data, ctxt, vars)

                else:
                    yield kind, data, pos

            else:
                if not stack:
                    break
                stream = pop()

    def _include(self, stream, ctxt, **vars):
        """Internal stream filter that performs inclusion of external
        template files.
        """
        from genshi.template.loader import TemplateNotFound

        for event in stream:
            if event[0] is INCLUDE:
                href, cls, fallback = event[1]
                if not isinstance(href, str):
                    parts = []
                    for subkind, subdata, subpos in self._flatten(
                            href, ctxt, **vars):
                        if subkind is TEXT:
                            parts.append(subdata)
                    href = ''.join([x for x in parts if x is not None])
                try:
                    tmpl = self.loader.load(href,
                                            relative_to=event[2][0],
                                            cls=cls or self.__class__)
                    for event in tmpl.generate(ctxt, **vars):
                        yield event
                except TemplateNotFound:
                    if fallback is None:
                        raise
                    for filter_ in self.filters:
                        fallback = filter_(iter(fallback), ctxt, **vars)
                    for event in fallback:
                        yield event
            else:
                yield event