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!')
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!')
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')
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 ")
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')
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)
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)
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')
def test_non_callable_attributes(self): view = Simple() view.thing = 'Chris' renderer = Renderer() actual = renderer.render(view) self.assertEqual(actual, "Hi Chris!")
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")
def test_higher_order_lambda(self): view = Lambdas() view.template = '{{#sort}}zyxwvutsrqponmlkjihgfedcba{{/sort}}' renderer = Renderer() actual = renderer.render(view) self.assertString(actual, u'abcdefghijklmnopqrstuvwxyz')
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 = {}
def test_non_callable_attributes(self): view = Simple() view.thing = 'Chris' renderer = Renderer() actual = renderer.render(view) self.assertEqual(actual, "Hi Chris!")
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()
def test_higher_order_rot13(self): view = Lambdas() view.template = '{{#rot13}}abcdefghijklm{{/rot13}}' renderer = Renderer() actual = renderer.render(view) self.assertString(actual, u'nopqrstuvwxyz')
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')
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)
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')
def test_higher_order_lambda(self): view = Lambdas() view.template = '{{#sort}}zyxwvutsrqponmlkjihgfedcba{{/sort}}' renderer = Renderer() actual = renderer.render(view) self.assertString(actual, u'abcdefghijklmnopqrstuvwxyz')
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')
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 ")
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")
def test_render__context(self): """ Test render(): passing a context. """ renderer = Renderer() self.assertEquals(renderer.render('Hi {{person}}', {'person': 'Mom'}), 'Hi Mom')
def test_higher_order_rot13(self): view = Lambdas() view.template = '{{#rot13}}abcdefghijklm{{/rot13}}' renderer = Renderer() actual = renderer.render(view) self.assertString(actual, u'nopqrstuvwxyz')
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)
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!')
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!")
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')
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!")
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))
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. """)
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 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. """)
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)
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!')
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!')
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!""", )
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")
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")
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)
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, {})
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")
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)
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")
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)
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)
def test_render__view(self): """ Test rendering a View instance. """ renderer = Renderer() view = Simple() actual = renderer.render(view) self.assertEqual('Hi pizza!', actual)
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>""")
def test_render__view(self): """ Test rendering a View instance. """ renderer = Renderer() view = Simple() actual = renderer.render(view) self.assertEqual('Hi pizza!', actual)
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)
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! ##""")
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>""")
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)}')
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)
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'), '')
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)
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')
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")
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")