Exemple #1
0
def render_str(src, **kw):
    from jinja2.environment import Environment
    env = Environment()
    parsed = Parser(env, src)
    gen = JsGenerator(env, '<internal>', '<internal>')
    gen.visit(parsed.parse())

    return render(source=gen.stream.getvalue(), **kw)
Exemple #2
0
    def parse(self, parser):
        """Execute parsing of md token and return nodes."""
        kwargs = None
        expected_heading_level = None
        count = 0
        while parser.stream.current.type != lexer.TOKEN_BLOCK_END:
            count = count + 1
            if count > self.max_tag_parse:
                raise err.TrestleError(
                    'Unexpected Jinja tag structure provided, please review docs.'
                )
            token = parser.stream.current
            if token.test('name:mdsection_include'):
                parser.stream.expect(lexer.TOKEN_NAME)
                markdown_source = parser.stream.expect(lexer.TOKEN_STRING)
                section_title = parser.stream.expect(lexer.TOKEN_STRING)
            elif kwargs is not None:
                arg = token.value
                next(parser.stream)
                parser.stream.expect(lexer.TOKEN_ASSIGN)
                token = parser.stream.current
                exp = self.parse_expression(parser)
                kwargs[arg] = exp.value
            else:
                if parser.stream.look().type == lexer.TOKEN_ASSIGN:
                    kwargs = {}
                continue
        # Use the established environment to source the file
        md_content, _, _ = self.environment.loader.get_source(
            self.environment, markdown_source.value)
        fm = frontmatter.loads(md_content)
        if not fm.metadata == {}:
            logger.warning(
                'Non zero metadata on MD section include - ignoring')
        full_md = markdown_node.MarkdownNode.build_tree_from_markdown(
            fm.content.split('\n'))
        md_section = full_md.get_node_for_key(section_title.value,
                                              strict_matching=True)
        # adjust
        if kwargs is not None:
            expected_heading_level = kwargs.get('heading_level')
        if expected_heading_level is not None:
            level = md_section.get_node_header_lvl()
            delta = int(expected_heading_level) - level
            if not delta == 0:
                md_section.change_header_level_by(delta)
        if not md_section:
            raise err.TrestleError(
                f'Unable to retrieve section "{section_title.value}"" from {markdown_source.value} jinja template.'
            )
        local_parser = Parser(self.environment, md_section.content.raw_text)
        top_level_output = local_parser.parse()

        return top_level_output.body
Exemple #3
0
    def parse(self, parser):
        """Execute parsing of md token and return nodes."""
        kwargs = None
        count = 0
        while parser.stream.current.type != lexer.TOKEN_BLOCK_END:
            count = count + 1
            token = parser.stream.current
            if count > self.max_tag_parse:
                raise err.TrestleError(
                    f'Unexpected Jinja tag structure provided at token {token.value}'
                )
            if token.test('name:md_datestamp'):
                parser.stream.expect(lexer.TOKEN_NAME)
            elif kwargs is not None:
                arg = token.value
                next(parser.stream)
                parser.stream.expect(lexer.TOKEN_ASSIGN)
                token = parser.stream.current
                exp = self.parse_expression(parser)
                kwargs[arg] = exp.value
            else:
                if parser.stream.look(
                ).type == lexer.TOKEN_ASSIGN or parser.stream.look(
                ).type == lexer.TOKEN_STRING:
                    kwargs = {}
                continue

        if kwargs is not None:
            if 'format' in kwargs and type(kwargs['format'] is str):
                date_string = date.today().strftime(kwargs['format'])
            else:
                date_string = date.today().strftime(
                    markdown_const.JINJA_DATESTAMP_FORMAT)
            if 'newline' in kwargs and kwargs['newline'] is False:
                pass
            else:
                date_string += '\n\n'
        else:
            date_string = date.today().strftime(
                markdown_const.JINJA_DATESTAMP_FORMAT) + '\n\n'

        local_parser = Parser(self.environment, date_string)
        datestamp_output = local_parser.parse()

        return datestamp_output.body
Exemple #4
0
    def parse(self, parser):
        """Execute parsing of md token and return nodes."""
        kwargs = None
        expected_heading_level = None
        count = 0
        while parser.stream.current.type != lexer.TOKEN_BLOCK_END:
            count = count + 1
            if count > self.max_tag_parse:
                raise err.TrestleError(
                    'Unexpected Jinja tag structure provided, please review docs.'
                )
            token = parser.stream.current
            if token.test('name:md_clean_include'):
                parser.stream.expect(lexer.TOKEN_NAME)
                markdown_source = parser.stream.expect(lexer.TOKEN_STRING)
            elif kwargs is not None:
                arg = token.value
                next(parser.stream)
                parser.stream.expect(lexer.TOKEN_ASSIGN)
                token = parser.stream.current
                exp = self.parse_expression(parser)
                kwargs[arg] = exp.value
            else:
                if parser.stream.look().type == lexer.TOKEN_ASSIGN:
                    kwargs = {}
                continue
        md_content, _, _ = self.environment.loader.get_source(
            self.environment, markdown_source.value)
        fm = frontmatter.loads(md_content)
        content = fm.content
        content += '\n\n'
        if kwargs is not None:
            expected_heading_level = kwargs.get('heading_level')
        if expected_heading_level is not None:
            content = adjust_heading_level(content, expected_heading_level)

        local_parser = Parser(self.environment, content)
        top_level_output = local_parser.parse()

        return top_level_output.body
Exemple #5
0
def dump_tpl(**ctx):
    """
    Here I`m compiling template into js code
    and dumping it to browser.

    Template selected by function "splash" which is 
    view function for "/".

    This handler called every time, somebody GETs /?js
    """
    from jinja2.parser import Parser
    from jscrap.generator import JsGenerator

    ret = []
    for tpl in env.loader.list_templates():
        source,_,_ = env.loader.get_source(env, tpl)
        code = Parser(env, source)
        gen = JsGenerator(env, tpl, tpl)
        gen.visit(code.parse())
        ret.append(gen.stream.getvalue())

    return ret, 'text/plain'
Exemple #6
0
 def js_compile(self, source, name):
     code = Parser(self.env, source)
     gen = JsGenerator(self.env, name, name)
     gen.visit(code.parse())
     return gen.stream.getvalue()
Exemple #7
0
 def jinja_compile(source, name, generator):
     code = Parser(env, source)
     gen = generator(env, name, name)
     gen.visit(code.parse())
     return gen.stream.getvalue()