Exemplo n.º 1
0
    def test_callables(self):
        view = Lambdas()
        view.template = '{{#replace_foo_with_bar}}foo != bar. oh, it does!{{/replace_foo_with_bar}}'

        renderer = Renderer()
        actual = renderer.render(view)
        self.assertString(actual, u'bar != bar. oh, it does!')
Exemplo n.º 2
0
    def test_callables(self):
        view = Lambdas()
        view.template = '{{#replace_foo_with_bar}}foo != bar. oh, it does!{{/replace_foo_with_bar}}'

        renderer = Renderer()
        actual = renderer.render(view)
        self.assertString(actual, u'bar != bar. oh, it does!')
Exemplo n.º 3
0
    def test_partials_with_lambda(self):
        view = Lambdas()
        view.template = '{{>partial_with_lambda}}'

        renderer = Renderer(search_dirs=EXAMPLES_DIR)
        actual = renderer.render(view)
        self.assertEqual(actual, u'nopqrstuvwxyz')
Exemplo n.º 4
0
    def test_looping_and_negation_context(self):
        template = '{{#item}}{{header}}: {{name}} {{/item}}{{^item}} Shouldnt see me{{/item}}'
        context = Complex()

        renderer = Renderer()
        actual = renderer.render(template, context)
        self.assertEqual(actual, "Colors: red Colors: green Colors: blue ")
Exemplo n.º 5
0
    def test_partials_with_lambda(self):
        view = Lambdas()
        view.template = '{{>partial_with_lambda}}'

        renderer = Renderer(search_dirs=EXAMPLES_DIR)
        actual = renderer.render(view)
        self.assertEqual(actual, u'nopqrstuvwxyz')
Exemplo n.º 6
0
    def export(self, template_file_name, output_file_name,
               sort="public", data=None, limit=0):
        """Export ranking to a file.

        Args:
            template_file_name (str): where is the template
                (moustache template)
            output_file_name (str): where create the file with the ranking
            sort (str): field to sort the users
        """
        exportedData = {}
        exportedUsers = self.getSortedUsers()
        template = self.__getTemplate(template_file_name)
        position = 1

        if not limit:
            exportedData["users"] = exportedUsers
        else:
            exportedData["users"] = exportedUsers[:limit]

        for u in exportedData["users"]:
            u["position"] = position
            u["comma"] = position < len(exportedData["users"])
            position += 1

        exportedData["extraData"] = data

        renderer = Renderer()
        output = renderer.render(template, exportedData)

        with open(output_file_name, "w") as text_file:
            text_file.write(output)
Exemplo n.º 7
0
class Plugin(BasePlugin):
    name = "pystache"

    defaults = dict(
        path = ("templates",),
        extension = "mustache",
        encoding = "utf-8",
        partials = None,
        layout = None,
    )

    def __init__(self, **options):
        super().__init__(**options)
        self.renderer = None

    def setup(self, app):
        super().setup(app)

        if isinstance(self.cfg.path, str):
            self.cfg.path = [self.cfg.path]
        self.cfg.path = [P.abspath(p) for p in self.cfg.path]
        self.renderer = Renderer(file_encoding=self.cfg.encoding,
                search_dirs=self.cfg.path,
                file_extension=self.cfg.extension,
                partials=self.cfg.partials)

    @coroutine
    def render(self, path, layout=None, *ctx, **kw):
        layout = self.cfg.layout if layout is None else layout
        if layout:
            kw["yield"] = self.renderer.render_name(path, *ctx, **kw)
            path = layout
        return self.renderer.render_name(path, *ctx, **kw)
Exemplo n.º 8
0
    def test_render__context_and_kwargs__precedence(self):
        """
        Test render(): **kwargs takes precedence over context.

        """
        renderer = Renderer()
        self.assertEquals(renderer.render('Hi {{person}}', {'person': 'Mom'}, person='Dad'), 'Hi Dad')
Exemplo n.º 9
0
    def test_non_callable_attributes(self):
        view = Simple()
        view.thing = 'Chris'

        renderer = Renderer()
        actual = renderer.render(view)
        self.assertEqual(actual, "Hi Chris!")
Exemplo n.º 10
0
    def test_nested_context(self):
        renderer = Renderer()
        view = NestedContext(renderer)
        view.template = '{{#foo}}{{thing1}} and {{thing2}} and {{outer_thing}}{{/foo}}{{^foo}}Not foo!{{/foo}}'

        actual = renderer.render(view)
        self.assertString(actual, u"one and foo and two")
Exemplo n.º 11
0
    def test_higher_order_lambda(self):
        view = Lambdas()
        view.template = '{{#sort}}zyxwvutsrqponmlkjihgfedcba{{/sort}}'

        renderer = Renderer()
        actual = renderer.render(view)
        self.assertString(actual, u'abcdefghijklmnopqrstuvwxyz')
Exemplo n.º 12
0
    def __init__(self,
                 pagePropertiesEditor,
                 templates={},
                 confluence=None,
                 pagePropertiesOrder=None,
                 **kwargs):
        self.editor = pagePropertiesEditor
        self.templates = templates
        self.confluence = confluence

        self.order = None
        if 'order' in kwargs:
            self.order = kwargs['order']
        if pagePropertiesOrder is not None:
            self.order = pagePropertiesOrder

        self.renderer = Renderer(
            search_dirs="{}/templates".format(dirname(__file__)),
            file_extension="mustache",
        )

        for t in ['user', 'page', 'link', 'list', 'value']:
            self.renderer.load_template(t)

        self.userkeys = {}
Exemplo n.º 13
0
    def test_non_callable_attributes(self):
        view = Simple()
        view.thing = 'Chris'

        renderer = Renderer()
        actual = renderer.render(view)
        self.assertEqual(actual, "Hi Chris!")
Exemplo n.º 14
0
    def __init__(self, contexts=None, nodefaults=None):
        """
        Initialize the config generator.

        @param templates A path to the directory where the configuration
            templtaes are stored.
        @param contexts A path to the context file. Defaults to None in which
            case you can add them manually or use load(). If this is a list
            then the config from each file will be loaded. Values in later
            files in the same context will override previous values.
        @param nodefaults A list/tuple of context names not to inject defaults
            for.
        """
        if nodefaults is None:
            nodefaults = ()
        self.renderer = Renderer()
        self.contexts = {'default': {}}
        self.nodefaults = nodefaults
        if contexts is not None:
            if hasattr(contexts, '__iter__'):
                for context in contexts:
                    self.load_context(context)
            else:
                self.load_context(contexts)
        self.load_defaults()
Exemplo n.º 15
0
    def test_higher_order_rot13(self):
        view = Lambdas()
        view.template = '{{#rot13}}abcdefghijklm{{/rot13}}'

        renderer = Renderer()
        actual = renderer.render(view)
        self.assertString(actual, u'nopqrstuvwxyz')
Exemplo n.º 16
0
    def test_hierarchical_partials_with_lambdas(self):
        view = Lambdas()
        view.template = '{{>partial_with_partial_and_lambda}}'

        renderer = Renderer(search_dirs=EXAMPLES_DIR)
        actual = renderer.render(view)
        self.assertString(actual, u'nopqrstuvwxyznopqrstuvwxyz')
Exemplo n.º 17
0
    def export(self,
               template_file_name,
               output_file_name,
               sort="public",
               data=None,
               limit=0):
        """Export ranking to a file.

        Args:
            template_file_name (str): where is the template
                (moustache template)
            output_file_name (str): where create the file with the ranking
            sort (str): field to sort the users
        """
        exportedData = {}
        exportedUsers = self.__exportUsers(sort, limit)

        exportedData["users"] = exportedUsers
        exportedData["extraData"] = data

        with open(template_file_name) as template_file:
            template_raw = template_file.read()

        template = parse(template_raw)
        renderer = Renderer()

        output = renderer.render(template, exportedData)

        with open(output_file_name, "w") as text_file:
            text_file.write(output)
Exemplo n.º 18
0
    def test_render__kwargs_and_no_context(self):
        """
        Test render(): passing **kwargs and no context.

        """
        renderer = Renderer()
        self.assertEquals(renderer.render('Hi {{person}}', person='Mom'), 'Hi Mom')
Exemplo n.º 19
0
    def test_higher_order_lambda(self):
        view = Lambdas()
        view.template = '{{#sort}}zyxwvutsrqponmlkjihgfedcba{{/sort}}'

        renderer = Renderer()
        actual = renderer.render(view)
        self.assertString(actual, u'abcdefghijklmnopqrstuvwxyz')
Exemplo n.º 20
0
    def test_hierarchical_partials_with_lambdas(self):
        view = Lambdas()
        view.template = '{{>partial_with_partial_and_lambda}}'

        renderer = Renderer(search_dirs=EXAMPLES_DIR)
        actual = renderer.render(view)
        self.assertString(actual, u'nopqrstuvwxyznopqrstuvwxyz')
Exemplo n.º 21
0
    def test_looping_and_negation_context(self):
        template = '{{#item}}{{header}}: {{name}} {{/item}}{{^item}} Shouldnt see me{{/item}}'
        context = Complex()

        renderer = Renderer()
        actual = renderer.render(template, context)
        self.assertEqual(actual, "Colors: red Colors: green Colors: blue ")
Exemplo n.º 22
0
    def test_nested_context(self):
        renderer = Renderer()
        view = NestedContext(renderer)
        view.template = '{{#foo}}{{thing1}} and {{thing2}} and {{outer_thing}}{{/foo}}{{^foo}}Not foo!{{/foo}}'

        actual = renderer.render(view)
        self.assertString(actual, u"one and foo and two")
Exemplo n.º 23
0
    def test_render__context(self):
        """
        Test render(): passing a context.

        """
        renderer = Renderer()
        self.assertEquals(renderer.render('Hi {{person}}', {'person': 'Mom'}), 'Hi Mom')
Exemplo n.º 24
0
    def test_higher_order_rot13(self):
        view = Lambdas()
        view.template = '{{#rot13}}abcdefghijklm{{/rot13}}'

        renderer = Renderer()
        actual = renderer.render(view)
        self.assertString(actual, u'nopqrstuvwxyz')
Exemplo n.º 25
0
    def test_render__return_type(self):
        """
        Check that render() returns a string of type unicode.

        """
        renderer = Renderer()
        rendered = renderer.render('foo')
        self.assertEquals(type(rendered), unicode)
Exemplo n.º 26
0
    def test_partial_in_partial_has_access_to_grand_parent_context(self):
        renderer = Renderer(search_dirs=EXAMPLES_DIR)

        view = TemplatePartial(renderer=renderer)
        view.template = '''{{>partial_in_partial}}'''

        actual = renderer.render(view, {'prop': 'derp'})
        self.assertEqual(actual, 'Hi derp!')
Exemplo n.º 27
0
    def test_nested_context_is_available_in_view(self):
        renderer = Renderer()

        view = NestedContext(renderer)
        view.template = "{{#herp}}{{#derp}}{{nested_context_in_view}}{{/derp}}{{/herp}}"

        actual = renderer.render(view)
        self.assertString(actual, u"it works!")
Exemplo n.º 28
0
    def test_render__context_and_kwargs(self):
        """
        Test render(): passing a context and **kwargs.

        """
        renderer = Renderer()
        template = 'Hi {{person1}} and {{person2}}'
        self.assertEquals(renderer.render(template, {'person1': 'Mom'}, person2='Dad'), 'Hi Mom and Dad')
Exemplo n.º 29
0
    def test_partial_in_partial_has_access_to_grand_parent_context(self):
        renderer = Renderer(search_dirs=EXAMPLES_DIR)

        view = TemplatePartial(renderer=renderer)
        view.template = """{{>partial_in_partial}}"""

        actual = renderer.render(view, {"prop": "derp"})
        self.assertEqual(actual, "Hi derp!")
Exemplo n.º 30
0
 def test_nonexist_formatter(self):
     renderer = Renderer()
     renderer.register_formatter('u', lambda x: x.upper())
     self.assertRaises(FormatterNotFoundError, renderer.render, '{{foo|x}}', {'foo': 'bar'})
     try:
         renderer.render('{{foo|x}}', {'foo': 'bar'})
     except FormatterNotFoundError as e:
         self.assertString('None:1.0', str(e.location))
Exemplo n.º 31
0
    def test_delimiters(self):
        renderer = Renderer()
        actual = renderer.render(Delimiters())
        self.assertString(actual, u"""\
* It worked the first time.
* And it worked the second time.
* Then, surprisingly, it worked the third time.
""")
Exemplo n.º 32
0
 def __init__(self, handler, search_dirs, caching=True):
     super(MustacheRenderer, self).__init__(handler)
     if caching:
         self.renderer = CachedRenderer(
             handler.application.cache,
             search_dirs=search_dirs)
     else:
         self.renderer = PystacheRenderer(search_dirs=search_dirs)
Exemplo n.º 33
0
    def test_delimiters(self):
        renderer = Renderer()
        actual = renderer.render(Delimiters())
        self.assertString(actual, u"""\
* It worked the first time.
* And it worked the second time.
* Then, surprisingly, it worked the third time.
""")
Exemplo n.º 34
0
    def _render_template(self, template_name, template_data = None, partials = None):
            
        r = Renderer(search_dirs=[ROOT_PATH+"/static/template/"],partials=partials)
        
        template_data = self._add_in_default_data(template_data)
        

        return r.render_name(template_name, template_data)
 def __init__(self, template_dir, template_file):
     """Create a new PystacheMessageBuilder that uses the specified template file.
     :param template_dir: The directory to load template files from
     :param template_file: The template file to populate with values.
     """
     self._renderer = Renderer(search_dirs=template_dir)
     raw_template = self._renderer.load_template(template_file)
     self._parsed_template = pystache.parse(raw_template)
Exemplo n.º 36
0
    def test_nested_context_is_available_in_view(self):
        renderer = Renderer()

        view = NestedContext(renderer)
        view.template = '{{#herp}}{{#derp}}{{nested_context_in_view}}{{/derp}}{{/herp}}'

        actual = renderer.render(view)
        self.assertString(actual, 'it works!')
Exemplo n.º 37
0
    def test_partial_in_partial_has_access_to_grand_parent_context(self):
        renderer = Renderer(search_dirs=EXAMPLES_DIR)

        view = TemplatePartial(renderer=renderer)
        view.template = '''{{>partial_in_partial}}'''

        actual = renderer.render(view, {'prop': 'derp'})
        self.assertEqual(actual, 'Hi derp!')
Exemplo n.º 38
0
    def test_template_partial(self):
        renderer = Renderer(search_dirs=EXAMPLES_DIR)
        actual = renderer.render(TemplatePartial(renderer=renderer))

        self.assertString(
            actual,
            u"""<h1>Welcome</h1>
Again, Welcome!""",
        )
Exemplo n.º 39
0
    def test_make_resolve_partial__parsed(self):
        """
        Test _make_resolve_partial__parsed(): that we can take ParsedTemplates as partials

        """
        partials = {"partial": parse(u"Hello, {{person}}")}
        renderer = Renderer(partials=partials)
        actual = renderer.render(u"{{>partial}}", {"person": "foo"})
        self.assertString(actual, u"Hello, foo")
Exemplo n.º 40
0
    def test_render_path(self):
        """
        Test the render_path() method.

        """
        renderer = Renderer()
        path = get_data_path('say_hello.mustache')
        actual = renderer.render_path(path, to='foo')
        self.assertEqual(actual, "Hello, foo")
Exemplo n.º 41
0
    def test__make_loader__return_type(self):
        """
        Test that _make_loader() returns a Loader.

        """
        renderer = Renderer()
        loader = renderer._make_loader()

        self.assertEquals(type(loader), Loader)
Exemplo n.º 42
0
    def test_render__kwargs_does_not_modify_context(self):
        """
        Test render(): passing **kwargs does not modify the passed context.

        """
        context = {}
        renderer = Renderer()
        renderer.render('Hi {{person}}', context=context, foo="bar")
        self.assertEquals(context, {})
Exemplo n.º 43
0
    def test_render_path(self):
        """
        Test the render_path() method.

        """
        renderer = Renderer()
        path = get_data_path('say_hello.mustache')
        actual = renderer.render_path(path, to='foo')
        self.assertEqual(actual, "Hello, foo")
Exemplo n.º 44
0
 def prepare(self, **options):
     from pystache import Renderer
     self.context = threading.local()
     self.context.vars = {}
     if hasattr(self, "layout"):
         self.layout_filename = self.search(self.layout, self.lookup)
     self.tpl = Renderer(search_dirs=self.lookup,
             file_encoding=self.encoding, string_encoding=self.encoding,
             **options)
Exemplo n.º 45
0
    def test_make_resolve_partial__parsed(self):
        """
        Test _make_resolve_partial__parsed(): that we can take ParsedTemplates as partials

        """
        partials = {"partial": parse(u"Hello, {{person}}")}
        renderer = Renderer(partials=partials)
        actual = renderer.render(u"{{>partial}}", {"person": "foo"})
        self.assertString(actual, u"Hello, foo")
Exemplo n.º 46
0
class MustacheRenderer(BaseRenderer):
    def __init__(self, handler, search_dirs, caching=True):
        super(MustacheRenderer, self).__init__(handler)
        if caching:
            self.renderer = CachedRenderer(
                handler.application.cache,
                search_dirs=search_dirs)
        else:
            self.renderer = PystacheRenderer(search_dirs=search_dirs)

    def _default_template_variables(self, kwargs):
        super(MustacheRenderer, self)._default_template_variables(kwargs)
        kwargs['xsrf_form_html'] = self.handler.xsrf_form_html()

    def add_options_variables(self, kwargs):
        kwargs['class_options_debug_html'] = 'debug' \
            if options.debug_html else ''
        kwargs['js_debug'] = 'true' \
            if options.debug else 'false'
        for option in options._options:
            kwargs['option_' + option] = getattr(options, option)

    def render_string_template(self, string_template, **kwargs):
        self._default_template_variables(kwargs)
        self.add_options_variables(kwargs)
        return self.renderer.render(string_template, kwargs)

    def render(self, template_name, context=None, **kwargs):
        # template_name = "".join(template_name.split('.')[:-1])
        self._default_template_variables(kwargs)
        self.add_options_variables(kwargs)
        kwargs['block_css'] = self.block_css
        kwargs['block_javascript'] = self.block_javascript
        return self.renderer.render_name(
            template_name, context or self.handler, **kwargs)

    def block_css(self, text, *args, **kwargs):
        css_includes = load_json(text)
        csses = []
        for css_args in css_includes:
            csses.append(self.add_css(**css_args))
        return "\n".join(csses)

    def block_javascript(self, text, *args, **kwargs):
        js_includes = load_json(text)
        jses = []
        for js_args in js_includes:
            jses.append(self.add_javascript(**js_args))
        return "\n".join(jses)

    def render_error(self, *args, **kwargs):
        kwargs['option_debug?'] = options.debug
        error_template = self.renderer.render_name(
            "error", self.handler, *args, **kwargs)

        return self.render("base", block_content=error_template)
Exemplo n.º 47
0
    def test__missing_tags__unknown_value(self):
        """
        Check missing_tags attribute: setting an unknown value.

        """
        renderer = Renderer()
        renderer.missing_tags = 'foo'

        self.assertException(Exception, "Unsupported 'missing_tags' value: 'foo'",
                             renderer._make_render_engine)
Exemplo n.º 48
0
    def test_render__view(self):
        """
        Test rendering a View instance.

        """
        renderer = Renderer()

        view = Simple()
        actual = renderer.render(view)
        self.assertEqual('Hi pizza!', actual)
Exemplo n.º 49
0
    def test_complex(self):
        renderer = Renderer()
        actual = renderer.render(Complex())
        self.assertString(actual, u"""\
<h1>Colors</h1>
<ul>
<li><strong>red</strong></li>
<li><a href="#Green">green</a></li>
<li><a href="#Blue">blue</a></li>
</ul>""")
Exemplo n.º 50
0
    def test_render__view(self):
        """
        Test rendering a View instance.

        """
        renderer = Renderer()

        view = Simple()
        actual = renderer.render(view)
        self.assertEqual('Hi pizza!', actual)
Exemplo n.º 51
0
def render_tpl(tpl, ctx=None, search_dirs=None):
    if search_dirs is None:
        search_dirs = 'tpl'
    kw = {
        'file_extension': False,
        'search_dirs': search_dirs,
        'missing_tags': 'strict'
    }
    renderer = Renderer(**kw)
    return renderer.render(tpl, ctx)
Exemplo n.º 52
0
    def test_template_partial_extension(self):
        renderer = Renderer(search_dirs=EXAMPLES_DIR, file_extension='txt')

        view = TemplatePartial(renderer=renderer)

        actual = renderer.render(view)
        self.assertString(actual, """Welcome
-------

## Again, Welcome! ##""")
Exemplo n.º 53
0
    def test_complex(self):
        renderer = Renderer()
        actual = renderer.render(Complex())
        self.assertString(actual, u"""\
<h1>Colors</h1>
<ul>
<li><strong>red</strong></li>
<li><a href="#Green">green</a></li>
<li><a href="#Blue">blue</a></li>
</ul>""")
Exemplo n.º 54
0
def generate_report(ldd_summary, pds4_version, pds4_alpha_version, output, config):
    _ldd_html_block = ""
    _ldd_toc = ""
    for _repo_name in ldd_summary.keys():
        _ldd_summary_repo = ldd_summary[_repo_name]
        _assets = _ldd_summary_repo['assets']
        _description = config[_ldd_summary_repo['repo'].name]['description']
        if _assets:
            _pystache_dict = {
                'ns_id': _ldd_summary_repo['ns_id'],
                'title': _ldd_summary_repo['name'],
                'description': _description,
                'release_date': datetime.strftime(_ldd_summary_repo['release'].published_at, '%m/%d/%Y'),
                'xsd_path': _assets['xsd'].replace(OUTPUT_PATH, ''),
                'xsd_fname': os.path.basename(_assets['xsd']),
                'sch_path': _assets['sch'].replace(OUTPUT_PATH, ''),
                'sch_fname': os.path.basename(_assets['sch']),
                'xml_path': _assets['xml'].replace(OUTPUT_PATH, ''),
                'xml_fname': os.path.basename(_assets['xml']),
                'json_path': _assets['json'].replace(OUTPUT_PATH, ''),
                'json_fname': os.path.basename(_assets['json']),
                'zip_path': _assets['zip'].replace(OUTPUT_PATH, ''),
                'zip_fname': os.path.basename(_assets['zip']),
                'issues_url': ISSUES_URL,
                'github_url': _ldd_summary_repo['repo'].homepage or
                              _ldd_summary_repo['repo'].clone_url.replace('.git', '')
            }
            _renderer = Renderer()
            _template = resource_string(__name__, os.path.join(LDD_TEMPLATES_DIR, 'ldd.template.html'))
            _ldd_html_block += _renderer.render(_template, _pystache_dict)
        else:
            # Discipline LDD was not release. use alternate template
            _pystache_dict = {
                'ns_id': _ldd_summary_repo['ns_id'],
                'title': _ldd_summary_repo['name'],
                'description': _description,
                'issues_url': ISSUES_URL,
                'github_url': _ldd_summary_repo['repo'].homepage or _ldd_summary_repo['repo'].clone_url.replace('.git', '')
            }
            _renderer = Renderer()
            _template = resource_string(__name__, os.path.join(LDD_TEMPLATES_DIR, 'ldd-alternate.template.html'))
            _ldd_html_block += _renderer.render(_template, _pystache_dict)

        # Build up LDD TOC
        _ldd_toc += LDD_TOC_TEMPLATE.format(_ldd_summary_repo['ns_id'], _ldd_summary_repo['name'])

    with open(os.path.join(output, LDD_REPORT), 'w') as f_out:
        _pystache_dict = {
            'ldd_block': _ldd_html_block,
            'ldd_toc': _ldd_toc,
            'pds4_version': pds4_version,
            'pds4_alpha_version': pds4_alpha_version
        }

        _renderer = Renderer()
        _template = resource_string(__name__, os.path.join(LDD_TEMPLATES_DIR, 'dd-summary.template.shtml'))
        html_str = _renderer.render(_template, _pystache_dict)
        f_out.write(html_str)

    logger.info(f'Output summary generated at: {os.path.join(output, LDD_REPORT)}')
Exemplo n.º 55
0
    def test__missing_tags__unknown_value(self):
        """
        Check missing_tags attribute: setting an unknown value.

        """
        renderer = Renderer()
        renderer.missing_tags = 'foo'

        self.assertException(Exception,
                             "Unsupported 'missing_tags' value: 'foo'",
                             renderer._make_render_engine)
Exemplo n.º 56
0
    def test__resolve_partial__not_found(self):
        """
        Check that resolve_partial returns the empty string when a template is not found.

        """
        renderer = Renderer()

        engine = renderer._make_render_engine()
        resolve_partial = engine.resolve_partial

        self.assertString(resolve_partial('foo'), '')
Exemplo n.º 57
0
    def _render_template(self,
                         template_name,
                         template_data=None,
                         partials=None):

        r = Renderer(search_dirs=[self._get_template_directory()],
                     partials=partials)

        template_data = self._add_in_default_data(template_data)

        return r.render_name(template_name, template_data)
Exemplo n.º 58
0
    def test_accessing_properties_on_parent_object_from_child_objects(self):
        parent = Thing()
        parent.this = 'derp'
        parent.children = [Thing()]
        view = Simple()
        view.template = "{{#parent}}{{#children}}{{this}}{{/children}}{{/parent}}"

        renderer = Renderer()
        actual = renderer.render(view, {'parent': parent})

        self.assertString(actual, u'derp')
Exemplo n.º 59
0
    def test__literal__handles_unicode(self):
        """
        Test that literal doesn't try to "double decode" unicode.

        """
        renderer = Renderer()
        renderer.string_encoding = 'ascii'

        engine = renderer._make_render_engine()
        literal = engine.literal

        self.assertEqual(literal("foo"), "foo")
Exemplo n.º 60
0
    def test__escape__uses_renderer_escape(self):
        """
        Test that escape uses the renderer's escape function.

        """
        renderer = Renderer()
        renderer.escape = lambda s: "**" + s

        engine = renderer._make_render_engine()
        escape = engine.escape

        self.assertEqual(escape("foo"), "**foo")