예제 #1
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)}')
예제 #2
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))
예제 #3
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, {})
예제 #4
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))
예제 #5
0
    def test_rendering_partial(self):
        renderer = Renderer(search_dirs=EXAMPLES_DIR)

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

        actual = renderer.render(view)
        self.assertString(actual, u'Again, Welcome!')

        view.template = '{{#looping}}{{>inner_partial}} {{/looping}}'
        actual = renderer.render(view)
        self.assertString(actual, u"Again, Welcome! Again, Welcome! Again, Welcome! ")
예제 #6
0
    def test_rendering_partial(self):
        renderer = Renderer(search_dirs=EXAMPLES_DIR)

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

        actual = renderer.render(view)
        self.assertString(actual, 'Again, Welcome!')

        view.template = '{{#looping}}{{>inner_partial}} {{/looping}}'
        actual = renderer.render(view)
        self.assertString(actual, "Again, Welcome! Again, Welcome! Again, Welcome! ")
예제 #7
0
    def test_render__object(self):
        """
        Test rendering an object instance.

        """
        renderer = Renderer()

        say_hello = SayHello()
        actual = renderer.render(say_hello)
        self.assertEqual('Hello, World', actual)

        actual = renderer.render(say_hello, to='Mars')
        self.assertEqual('Hello, Mars', actual)
예제 #8
0
    def test_render__object(self):
        """
        Test rendering an object instance.

        """
        renderer = Renderer()

        say_hello = SayHello()
        actual = renderer.render(say_hello)
        self.assertEqual('Hello, World', actual)

        actual = renderer.render(say_hello, to='Mars')
        self.assertEqual('Hello, Mars', actual)
예제 #9
0
    def test_render__nonascii_template(self):
        """
        Test passing a non-unicode template with non-ascii characters.

        """
        renderer = Renderer()
        template = "déf"

        # Check that decode_errors and string_encoding are both respected.
        renderer.decode_errors = 'ignore'
        renderer.string_encoding = 'ascii'
        self.assertEquals(renderer.render(template), "df")

        renderer.string_encoding = 'utf_8'
        self.assertEquals(renderer.render(template), u"déf")
예제 #10
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')
예제 #11
0
    def test_template_path_for_partials(self):
        """
        Test that View.template_rel_path is respected for partials.

        """
        spec = TemplateSpec()
        spec.template = "Partial: {{>tagless}}"

        renderer1 = Renderer()
        renderer2 = Renderer(search_dirs=EXAMPLES_DIR)

        actual = renderer1.render(spec)
        self.assertString(actual, u"Partial: ")

        actual = renderer2.render(spec)
        self.assertEqual(actual, "Partial: No tags...")
예제 #12
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")
예제 #13
0
    def test_non_callable_attributes(self):
        view = Simple()
        view.thing = 'Chris'

        renderer = Renderer()
        actual = renderer.render(view)
        self.assertEqual(actual, "Hi Chris!")
예제 #14
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!')
예제 #15
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')
예제 #16
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 ")
예제 #17
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!')
예제 #18
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 ")
예제 #19
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)
예제 #20
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')
예제 #21
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)
예제 #22
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')
예제 #23
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')
예제 #24
0
    def test_template_path_for_partials(self):
        """
        Test that View.template_rel_path is respected for partials.

        """
        spec = TemplateSpec()
        spec.template = "Partial: {{>tagless}}"

        renderer1 = Renderer()
        renderer2 = Renderer(search_dirs=EXAMPLES_DIR)

        actual = renderer1.render(spec)
        self.assertString(actual, "Partial: ")

        actual = renderer2.render(spec)
        self.assertEqual(actual, "Partial: No tags...")
예제 #25
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')
예제 #26
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')
예제 #27
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')
예제 #28
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')
예제 #29
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")
예제 #30
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')
예제 #31
0
    def test_render__context(self):
        """
        Test render(): passing a context.

        """
        renderer = Renderer()
        self.assertEquals(renderer.render('Hi {{person}}', {'person': 'Mom'}), 'Hi Mom')
예제 #32
0
    def test_non_callable_attributes(self):
        view = Simple()
        view.thing = 'Chris'

        renderer = Renderer()
        actual = renderer.render(view)
        self.assertEqual(actual, "Hi Chris!")
예제 #33
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!')
예제 #34
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)
예제 #35
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.
""")
예제 #36
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')
예제 #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!")
예제 #38
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!")
예제 #39
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!')
예제 #40
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!')
예제 #41
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.
""")
예제 #42
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!""",
        )
예제 #43
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")
예제 #44
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")
예제 #45
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)
예제 #46
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>""")
예제 #47
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, u"""Welcome
-------

## Again, Welcome! ##""")
예제 #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)
예제 #49
0
    def test_render__view(self):
        """
        Test rendering a View instance.

        """
        renderer = Renderer()

        view = Simple()
        actual = renderer.render(view)
        self.assertEqual('Hi pizza!', actual)
예제 #50
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>""")
예제 #51
0
파일: cli.py 프로젝트: petrjasek/fireq
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)
예제 #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! ##""")
예제 #53
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')
예제 #54
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')
예제 #55
0
def md_to_html(in_file, out_file, template_kargs):
    with open(in_file, 'r') as f_in:
        markdowner = Markdown()
        html_str = markdowner.convert(f_in.read())
        html_emojized_str = emoji.emojize(html_str, use_aliases=True)
        template_kargs['requirements_html'] = html_emojized_str
    renderer = Renderer()
    template = resource_string(__name__, 'REQUIREMENTS.html.template')
    with open(out_file, 'w') as f_out:
        html_str = renderer.render(template, template_kargs)
        f_out.write(html_str)
    return out_file
예제 #56
0
    def test_render__template_spec(self):
        """
        Test rendering a TemplateSpec instance.

        """
        renderer = Renderer()

        class Spec(TemplateSpec):
            template = "hello, {{to}}"
            to = 'world'

        spec = Spec()
        actual = renderer.render(spec)
        self.assertString(actual, 'hello, world')
예제 #57
0
def render_html(dst, config, soups, precomputed, template):
  soup = soups[dst]
  renderer = Renderer()
  title = precomputed.page[dst].title
  topdots = '../' * dst.count('/')
  body_html = '{}'.format(soup.body) if soup.body else '{}'.format(soup)
  html = renderer.render(template,
                         body_html=body_html,
                         generated=generate_generated(config, dst),
                         site_toc=generate_site_toc(config, precomputed, dst),
                         has_page_toc=bool(precomputed.page[dst].toc),
                         page_path=dst,
                         page_toc=precomputed.page[dst].toc,
                         title=title,
                         topdots=topdots)
  return html
예제 #58
0
    def test_custom_string_coercion_via_subclassing(self):
        """
        Test that string coercion can be customized via subclassing.

        """
        class MyRenderer(Renderer):
            def str_coerce(self, val):
                if not val:
                    return ''
                else:
                    return str(val)

        renderer1 = Renderer()
        renderer2 = MyRenderer()

        self.assertEqual(renderer1.render('{{value}}', value=None), 'None')
        self.assertEqual(renderer2.render('{{value}}', value=None), '')
예제 #59
0
    def test_template_rel_directory(self):
        """
        Test that View.template_rel_directory is respected.

        """
        class Tagless(TemplateSpec):
            pass

        view = Tagless()
        renderer = Renderer()

        self.assertRaises(TemplateNotFoundError, renderer.render, view)

        # TODO: change this test to remove the following brittle line.
        view.template_rel_directory = "examples"
        actual = renderer.render(view)
        self.assertEqual(actual, "No tags...")
class PystacheMessageBuilder:
    """A component that uses Pystache to populate a Mustache template in order to build a message."""

    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)

    def build_message(self, message_dictionary):
        """Build a message by populating a Mustache template with values from the provided dictionary.
        :param message_dictionary: The dictionary of values to use when populating the template.
        :return: A string containing a message suitable for sending to a remote MHS.
        """
        return self._renderer.render(self._parsed_template, message_dictionary)