Пример #1
0
def render(template_name,
           variables,
           template_dir='templates',
           file_ext=".mustache"):
    """
	Render a mustache template given a dict representing its variables.

	Args:
		template_name (str): the name of the template to be rendered
		variables (dict): a string -> any dict holding values of variables used in the template
		template_dir (str): the template directory, relative to the GitDox root directory.
							Defaults to 'templates'
		file_ext (str): the file extension of templates. Defaults to '.mustache'

	Returns:
		str: rendered HTML.
	"""
    template_dir = prefix + template_dir

    # load Mustache templates so we can reference them in our large templates
    templates = dict([(filename[:-len(file_ext)],
                       open(template_dir + os.sep + filename, 'r').read())
                      for filename in os.listdir(template_dir)
                      if filename.endswith(file_ext)])
    renderer = Renderer(partials=templates)

    variables['skin_stylesheet'] = config['skin']
    variables['navbar_html'] = get_menu()
    return renderer.render_path(
        template_dir + os.sep + template_name + file_ext, variables)
Пример #2
0
    def test(self):
        template = testData['template']
        partials = testData.has_key('partials') and testData['partials'] or {}
        expected = testData['expected']
        data     = testData['data']

        # Convert code strings to functions.
        # TODO: make this section of code easier to understand.
        new_data = {}
        for key, val in data.iteritems():
            if isinstance(val, dict) and val.get('__tag__') == 'code':
                val = eval(val['python'])
            new_data[key] = val

        renderer = Renderer(partials=partials)
        actual = renderer.render(template, new_data)
        actual = actual.encode('utf-8')

        message = """%s

  Template: \"""%s\"""

  Expected: %s
  Actual:   %s

  Expected: \"""%s\"""
  Actual:   \"""%s\"""
  """ % (description, template, repr(expected), repr(actual), expected, actual)

        self.assertEquals(actual, expected, message)
Пример #3
0
def render(template, context=None, **kwargs):
    """
    Return the given template string rendered using the given context.

    """
    renderer = Renderer()
    return renderer.render(template, context, **kwargs)
Пример #4
0
def render(template, context=None, **kwargs):
    """
    Return the given template string rendered using the given context.

    """
    renderer = Renderer()
    return renderer.render(template, context, **kwargs)
Пример #5
0
    def test_read__decode_errors(self):
        filename = 'nonascii.mustache'
        renderer = Renderer()

        self.assertRaises(UnicodeDecodeError, self._read, renderer, filename)
        renderer.decode_errors = 'ignore'
        actual = self._read(renderer, filename)
        self.assertEquals(actual, 'non-ascii: ')
Пример #6
0
def render(template, context=None, name=None, **kwargs):
    """
    Return the given template string rendered using the given context.

    """
    renderer = Renderer()
    parsed_template = parse(template, name=name)
    return renderer.render(parsed_template, context, **kwargs)
Пример #7
0
def render(template, context=None, name=None, **kwargs):
    """
    Return the given template string rendered using the given context.

    """
    renderer = Renderer()
    parsed_template = parse(template, name=name)
    return renderer.render(parsed_template, context, **kwargs)
Пример #8
0
def crear_plantilla(archivo_fuente='user.c'):
    print "creando plantilla para archivo %s" % archivo_fuente
    renderer = Renderer()
    template = renderer.load_template(SOURCE_TEMPLATE)
    dato_plantilla = renderer.render(template, {'include_path': archivo_fuente})
    archivo = open(SOURCE_FILE, 'w')
    archivo.write(dato_plantilla)
    archivo.close()
    print "plantilla creada"
    def _engine(self):
        """
        Create and return a default RenderEngine for testing.

        """
        renderer = Renderer(string_encoding='utf-8', missing_tags='strict')
        engine = renderer._make_render_engine()

        return engine
Пример #10
0
    def _engine(self):
        """
        Create and return a default RenderEngine for testing.

        """
        renderer = Renderer(string_encoding='utf-8', missing_tags='strict')
        engine = renderer._make_render_engine()

        return engine
Пример #11
0
    def test_read__file_encoding(self):
        filename = 'nonascii.mustache'

        renderer = Renderer()
        renderer.file_encoding = 'ascii'

        self.assertRaises(UnicodeDecodeError, self._read, renderer, filename)
        renderer.file_encoding = 'utf-8'
        actual = self._read(renderer, filename)
        self.assertEquals(actual, u'non-ascii: é')
Пример #12
0
    def test_make_locator__file_extension(self):
        """
        Test that make_locator() respects the file_extension attribute.

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

        locator = renderer.make_locator()

        self.assertEquals(locator.template_extension, 'foo')
Пример #13
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.assertEquals(escape("foo"), "**foo")
Пример #14
0
    def test__escape__uses_renderer_unicode(self):
        """
        Test that escape uses the renderer's unicode function.

        """
        renderer = Renderer()
        renderer.unicode = lambda s: s.upper()

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

        self.assertEquals(escape("foo"), "FOO")
Пример #15
0
    def test__literal__handles_unicode(self):
        """
        Test that literal doesn't try to "double decode" unicode.

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

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

        self.assertEquals(literal(u"foo"), "foo")
Пример #16
0
    def test__literal__uses_renderer_unicode(self):
        """
        Test that literal uses the renderer's unicode function.

        """
        renderer = Renderer()
        renderer.unicode = lambda s: s.upper()

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

        self.assertEquals(literal("foo"), "FOO")
Пример #17
0
 def get(self):
     pass_phrase = self.authenticate_request()
     if pass_phrase:
         if self.check_setup():
             loader = Loader(extension='html', search_dirs=['view', 'view/setup'])
             renderer = Renderer(file_extension='html',
                 search_dirs=['view/partials', 'view/setup'])
             template = loader.load_name('setup')
             html = renderer.render(template, {"pass": pass_phrase})
             self.write(html)
         else:
             self.write("setup already completed.")
Пример #18
0
    def get(self, article_name):

        article_name = article_name.lower()

        if article_name in BaseController.articles:

            article = BaseController.articles[article_name]

            # if content has not modified since last request
            # send a 304 not modified status
            modified_header_key = "If-Modified-Since"
            if modified_header_key in self.request.headers:
                if (self.request.headers["If-Modified-Since"] ==
                        article['modified_date']):
                    self.set_status(304)
                    return

            if (BaseController.settings['enable_caching']
                    and article_name in BaseController.cached_articles):
                html = BaseController.cached_articles[article_name]
            else:
                view_model = {
                    "article": article,
                    "site_name": BaseController.settings['site_name']
                }
                self.attach_meta_data(view_model)

                loader = Loader(file_encoding='utf8',
                                extension='html',
                                search_dirs=[
                                    'view',
                                ])
                renderer = Renderer(file_encoding='utf8',
                                    file_extension='html',
                                    search_dirs=['view/partials'])
                template = loader.load_name('article')
                html = renderer.render(template, view_model)

                # cache the html
                BaseController.cached_articles[article_name] = html

            # set http caching headers
            if "http_caching_max_age" in BaseController.settings:
                max_age = BaseController.settings["http_caching_max_age"]
            else:
                max_age = 60
            self.set_header("Cache-control", "max-age=%s" % max_age)
            self.set_header("Last-Modified", article['modified_date'])
            self.write(html)

        else:
            raise tornado.web.HTTPError(404)
Пример #19
0
    def test_unicode__default_encoding(self):
        """
        Test that the default_encoding attribute is respected.

        """
        renderer = Renderer()
        s = "é"

        renderer.default_encoding = "ascii"
        self.assertRaises(UnicodeDecodeError, renderer.unicode, s)

        renderer.default_encoding = "utf-8"
        self.assertEquals(renderer.unicode(s), u"é")
Пример #20
0
    def test_make_load_partial(self):
        """
        Test the _make_load_partial() method.

        """
        renderer = Renderer()
        renderer.partials = {'foo': 'bar'}
        load_partial = renderer._make_load_partial()

        actual = load_partial('foo')
        self.assertEquals(actual, 'bar')
        self.assertEquals(type(actual), unicode, "RenderEngine requires that "
            "load_partial return unicode strings.")
Пример #21
0
    def generate_page(self, articles):
        view_model = {
                    "articles": articles,
                    "site_name": BaseController.settings["site_name"]
                    }
        self.attach_meta_data(view_model)

        loader = Loader(file_encoding='utf8', extension='html',
                        search_dirs=['view', ])
        renderer = Renderer(file_encoding='utf8', file_extension='html',
                            search_dirs=['view/partials'])
        template = loader.load_name('list')
        html = renderer.render(template, view_model)
        return html
Пример #22
0
 def get(self):
     pass_phrase = self.authenticate_request()
     if pass_phrase:
         if self.check_setup():
             loader = Loader(extension='html',
                             search_dirs=['view', 'view/setup'])
             renderer = Renderer(
                 file_extension='html',
                 search_dirs=['view/partials', 'view/setup'])
             template = loader.load_name('setup')
             html = renderer.render(template, {"pass": pass_phrase})
             self.write(html)
         else:
             self.write("setup already completed.")
Пример #23
0
    def get(self, article_name):

        article_name = article_name.lower()

        if article_name in BaseController.articles:

            article = BaseController.articles[article_name]

            # if content has not modified since last request
            # send a 304 not modified status
            modified_header_key = "If-Modified-Since"
            if modified_header_key in self.request.headers:
                if (self.request.headers["If-Modified-Since"] ==
                    article['modified_date']):
                    self.set_status(304)
                    return

            if (BaseController.settings['enable_caching'] and
                article_name in BaseController.cached_articles):
                html = BaseController.cached_articles[article_name]
            else:
                view_model = {
                "article": article,
                "site_name": BaseController.settings['site_name']
                }
                self.attach_meta_data(view_model)

                loader = Loader(file_encoding='utf8',
                                extension='html',
                                search_dirs=['view', ])
                renderer = Renderer(file_encoding='utf8',
                                    file_extension='html',
                                    search_dirs=['view/partials'])
                template = loader.load_name('article')
                html = renderer.render(template, view_model)

                # cache the html
                BaseController.cached_articles[article_name] = html

            # set http caching headers
            if "http_caching_max_age" in BaseController.settings:
                max_age = BaseController.settings["http_caching_max_age"]
            else:
                max_age = 60
            self.set_header("Cache-control", "max-age=%s" % max_age)
            self.set_header("Last-Modified", article['modified_date'])
            self.write(html)

        else:
            raise tornado.web.HTTPError(404)
Пример #24
0
    def test_unicode__decode_errors(self):
        """
        Test that the decode_errors attribute is respected.

        """
        renderer = Renderer()
        renderer.default_encoding = "ascii"
        s = "déf"

        renderer.decode_errors = "ignore"
        self.assertEquals(renderer.unicode(s), "df")

        renderer.decode_errors = "replace"
        # U+FFFD is the official Unicode replacement character.
        self.assertEquals(renderer.unicode(s), u'd\ufffd\ufffdf')
Пример #25
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 default_encoding are both respected.
        renderer.decode_errors = 'ignore'
        renderer.default_encoding = 'ascii'
        self.assertEquals(renderer.render(template), "df")

        renderer.default_encoding = 'utf_8'
        self.assertEquals(renderer.render(template), u"déf")
Пример #26
0
def render_templates(source_dir,
                     template_dir,
                     target_dir,
                     file_ext='yaml',
                     extras={}):
    data = load_config(source_dir, extras)
    renderer = Renderer(search_dirs=[template_dir],
                        file_extension=file_ext,
                        missing_tags='strict')
    for f in os.listdir(template_dir):
        fname, ext = os.path.splitext(f)
        if ext == ('.' + file_ext) and os.path.isfile(
                os.path.join(template_dir, f)):
            with open(os.path.join(target_dir, f), 'w') as o:
                o.write(renderer.render_name(fname, data))
Пример #27
0
    def render(self, content, data):
        """
        Render the given ``content`` as template with the ``data`` dictionary.

        Args:
            content (str): The template content to render.
            data (dict): The data dictionary to render.

        Returns:
            str: The rendered template text

        """

        stache = Renderer(partials=self._partials_loader)
        return stache.render(content, data)
Пример #28
0
    def render(self, content, data):
        """
        Render the given ``content`` as template with the ``data`` dictionary.

        Args:
            content (str): The template content to render.
            data (dict): The data dictionary to render.

        Returns:
            str: The rendered template text

        """

        stache = Renderer(partials=self._partials_loader)
        return stache.render(content, data)
Пример #29
0
    def test_default_encoding__default(self):
        """
        Check the default value.

        """
        renderer = Renderer()
        self.assertEquals(renderer.default_encoding, sys.getdefaultencoding())
Пример #30
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')
Пример #31
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')
Пример #32
0
    def test_partials(self):
        """
        Test that the attribute is set correctly.

        """
        renderer = Renderer(partials={'foo': 'bar'})
        self.assertEquals(renderer.partials, {'foo': 'bar'})
Пример #33
0
    def test_escape__default(self):
        escape = Renderer().escape

        self.assertEquals(escape(">"), ">")
        self.assertEquals(escape('"'), """)
        # Single quotes are not escaped.
        self.assertEquals(escape("'"), "'")
Пример #34
0
    def test__load_partial__not_found(self):
        """
        Check that load_partial provides a nice message when a template is not found.

        """
        renderer = Renderer()
        renderer.partials = {}

        engine = renderer._make_render_engine()
        load_partial = engine.load_partial

        try:
            load_partial("foo")
            raise Exception("Shouldn't get here")
        except Exception, err:
            self.assertEquals(str(err), "Partial not found with name: 'foo'")
Пример #35
0
    def test_default_encoding(self):
        """
        Check that the constructor sets the attribute correctly.

        """
        renderer = Renderer(default_encoding="foo")
        self.assertEquals(renderer.default_encoding, "foo")
Пример #36
0
    def test_decode_errors__default(self):
        """
        Check the default value.

        """
        renderer = Renderer()
        self.assertEquals(renderer.decode_errors, 'strict')
Пример #37
0
    def test_decode_errors(self):
        """
        Check that the constructor sets the attribute correctly.

        """
        renderer = Renderer(decode_errors="foo")
        self.assertEquals(renderer.decode_errors, "foo")
Пример #38
0
    def test_file_encoding__default(self):
        """
        Check the file_encoding default.

        """
        renderer = Renderer()
        self.assertEquals(renderer.file_encoding, renderer.default_encoding)
Пример #39
0
    def test_file_encoding(self):
        """
        Check that the file_encoding attribute is set correctly.

        """
        renderer = Renderer(file_encoding='foo')
        self.assertEquals(renderer.file_encoding, 'foo')
Пример #40
0
    def test_make_load_partial__unicode(self):
        """
        Test _make_load_partial(): that load_partial doesn't "double-decode" Unicode.

        """
        renderer = Renderer()

        renderer.partials = {'partial': 'foo'}
        load_partial = renderer._make_load_partial()
        self.assertEquals(load_partial("partial"), "foo")

        # Now with a value that is already unicode.
        renderer.partials = {'partial': u'foo'}
        load_partial = renderer._make_load_partial()
        # If the next line failed, we would get the following error:
        #   TypeError: decoding Unicode is not supported
        self.assertEquals(load_partial("partial"), "foo")
Пример #41
0
    def test__escape__has_access_to_original_unicode_subclass(self):
        """
        Test that escape receives strings with the unicode subclass intact.

        """
        renderer = Renderer()
        renderer.escape = lambda s: type(s).__name__

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

        class MyUnicode(unicode):
            pass

        self.assertEquals(escape("foo"), "unicode")
        self.assertEquals(escape(u"foo"), "unicode")
        self.assertEquals(escape(MyUnicode("foo")), "MyUnicode")
Пример #42
0
    def __init__(self, **kw):
        """
        Initialize the template renderer.

        :param directories: Keyword parameter. A list of directories used as
            the search path for templates.
        """
        self.renderer = Renderer(search_dirs=kw['directories'])
        TemplateEngine.__init__(self, **kw)
Пример #43
0
    def render(self, data_dict, template):
        """
        Take a data dictionary and render it using the given template file.

        Required Arguments:

        :param data_dict: The data dictionary to render.
        :param template: The path to the template, after the
         ``template_module`` or ``template_dirs`` prefix as defined in the
         application.
        :returns: str (the rendered template text)

        """

        LOG.debug("rendering output using '%s' as a template." % template)
        content = self.load_template(template)
        stache = Renderer(partials=self._partials_loader)
        return stache.render(content, data_dict)
Пример #44
0
def main(sys_argv=sys.argv):
    template, context, c_format, multiple = parse_args(sys_argv, USAGE)

    if template.endswith('.mustache'):
        template = template[:-9]

    renderer = Renderer()

    try:
        template = renderer.load_template(template)
    except TemplateNotFoundError:
        pass

    if context.endswith(".csv") or (c_format and (c_format == "csv")):
        try:
            context = csv.DictReader(open(context, 'rb'))#, delimiter=',', quotechar='"')
        except IOError:
            print('ERROR: Could not parse context as CSV file. Check usage for input format options')
            exit(-1)            
    else:
        try:
            context = json.load(open(context))
        except IOError:
            context = json.loads(context)
        except ValueError: #likely a not well-formed JSON string, or user forgot -f csv.
            print('ERROR: Could not parse context as JSON file or text, check usage for input format options')
            exit(1)

    if (multiple):
        print ("multiple render on field %s" % multiple)
        fileName, fileExt = os.path.splitext(multiple)
        for i,c in enumerate(context):
            if multiple in c:
                f_name = str(c[multiple])
            else:                
                f_name = "%s-%03d%s" % (fileName, i, fileExt)
            with open(f_name, "w") as f: # mode "wx" could be used to prevent overwriting, + pass IOError, adding "--force" option to override.
                rendered = renderer.render(template, c)
                f.write(rendered)
                print ("%s done") % f_name
    else:
        rendered = renderer.render(template, context)
        print rendered
Пример #45
0
def main(sys_argv=sys.argv):
    template, context = parse_args(sys_argv, USAGE)

    if template.endswith('.mustache'):
        template = template[:-9]

    renderer = Renderer()

    try:
        template = renderer.load_template(template)
    except IOError:
        pass

    try:
        context = json.load(open(context))
    except IOError:
        context = json.loads(context)

    rendered = renderer.render(template, context)
    print rendered
Пример #46
0
    def test__literal__returns_unicode(self):
        """
        Test that literal returns unicode (and not a subclass).

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

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

        self.assertEquals(type(literal("foo")), unicode)

        class MyUnicode(unicode):
            pass

        s = MyUnicode("abc")

        self.assertEquals(type(s), MyUnicode)
        self.assertTrue(isinstance(s, unicode))
        self.assertEquals(type(literal(s)), unicode)
Пример #47
0
def main(argv=None):
    if argv is None:
        argv = sys.argv

    template, context, options = parse_args(argv, USAGE)

    if context is None and not sys.stdin.isatty():
        user_context, _ = read_yaml_frontmatter(sys.stdin)
    elif context:
        content = arg2text(context)
        user_context, _ = extract_context(content, greedy=True)
    else:
        user_context = {}

    # assuming first arg is a filename or template literal
    template = arg2text(template)
    template_context, template = extract_context(template)
    template_context.update(user_context)
    renderer = Renderer()
    rendered = renderer.render(template, template_context)
    print(rendered.encode('utf-8'))
Пример #48
0
    def _runTest(self):
        context = self._context
        description = self._description
        expected = self._expected
        file_path = self._file_path
        partials = self._partials
        template = self._template
        test_name = self._test_name

        renderer = Renderer(partials=partials)
        actual = renderer.render(template, context)

        # We need to escape the strings that occur in our format string because
        # they can contain % symbols, for example (in delimiters.yml)--
        #
        #   "template: '{{=<% %>=}}(<%text%>)'"
        #
        def escape(s):
            return s.replace("%", "%%")

        parser_info = _get_parser_info()
        subs = [repr(test_name), description, os.path.abspath(file_path),
                template, repr(context), parser_info]
        subs = tuple([escape(sub) for sub in subs])
        # We include the parsing module version info to help with troubleshooting
        # yaml/json/simplejson issues.
        message = """%s: %s

  File: %s

  Template: \"""%s\"""

  Context: %s

  %%s

  [using %s]
  """ % subs

        self.assertString(actual, expected, format=message)