Ejemplo n.º 1
0
 def parse(self, parser):
     lineno = next(parser.stream).lineno
     parts = [parser.stream.expect('name').value]
     while parser.stream.current.type != 'block_end':
         parser.stream.expect('dot')
         parts.append(parser.stream.expect('name').value)
     body = parser.parse_statements(['name:endeditable'], drop_needle=True)
     call = self.call_method(
         '_editable_loader',
         [nodes.Name(parts[-2], 'load'),
          nodes.Const(parts[-1])])
     output_nodes = [
         nodes.Output([
             nodes.MarkSafe(
                 nodes.TemplateData('<div class="editable-container">')),
             nodes.MarkSafe(
                 nodes.TemplateData('<div class="editable-content">'))
         ])
     ]
     output_nodes.extend(body)
     output_nodes.extend([
         nodes.Output([nodes.MarkSafe(nodes.TemplateData('</div>'))]),
         nodes.Output([nodes.MarkSafe(call)]),
         nodes.Output([nodes.MarkSafe(nodes.TemplateData('</div>'))])
     ])
     block_name = '%s_%s_%d' % (parts[-2], parts[-1], random.randint(
         0, 500))
     return nodes.Block(block_name, output_nodes, True)
Ejemplo n.º 2
0
    def parse(self, parser):
        lineno = parser.stream.next().lineno

        return [
            nodes.Output([
                nodes.TemplateData(
                    '<input type="hidden" name="csrfmiddlewaretoken" value="'),
                nodes.Name('csrf_token', 'load'),
                nodes.TemplateData('" />'),
            ]).set_lineno(lineno)
        ]
Ejemplo n.º 3
0
    def parse(self, parser):
        next(parser.stream)

        name = parser.parse_expression()

        body = parser.parse_statements(['name:endcase'], drop_needle=True)
        body.append(nodes.TemplateData('\n\n'))

        return body
Ejemplo n.º 4
0
    def parse(self, parser):
        parser.stream.next()
        args = [parser.parse_expression()]
        if parser.stream.skip_if('comma'):
            args.append(parser.parse_expression())
        else:
            args.append(nodes.Const(None))

        gist_id = "%s/%s" % (args[0].left.name, args[0].right.value)
        node = nodes.TemplateData()
        node.data = '<script src="https://gist.github.com/%s.js"></script>' % gist_id
        return node
Ejemplo n.º 5
0
    def parse(self, parser):
        next(parser.stream)

        thing = ''
        while not parser.stream.current.test_any('block_end'):
            thing += parser.stream.current.value
            parser.stream.next()
        print 'name: ' + thing
        #name = parser.parse_expression()
        #print name

        body = parser.parse_statements(['name:endcase'], drop_needle=True)
        body.append(nodes.TemplateData('\n\n'))

        return body
Ejemplo n.º 6
0
    def subparse(self, end_tokens=None):
        body = []
        data_buffer = []
        add_data = data_buffer.append

        if end_tokens is not None:
            self._end_token_stack.append(end_tokens)

        def flush_data():
            if data_buffer:
                lineno = data_buffer[0].lineno
                body.append(nodes.Output(data_buffer[:], lineno=lineno))
                del data_buffer[:]

        try:
            while self.stream:
                token = self.stream.current
                if token.type == 'data':
                    if token.value:
                        add_data(
                            nodes.TemplateData(token.value,
                                               lineno=token.lineno))
                    next(self.stream)
                elif token.type == 'variable_begin':
                    next(self.stream)
                    add_data(self.parse_tuple(with_condexpr=True))
                    self.stream.expect('variable_end')
                elif token.type == 'block_begin':
                    flush_data()
                    next(self.stream)
                    if end_tokens is not None and \
                       self.stream.current.test_any(*end_tokens):
                        return body
                    rv = self.parse_statement()
                    if isinstance(rv, list):
                        body.extend(rv)
                    else:
                        body.append(rv)
                    self.stream.expect('block_end')
                else:
                    raise AssertionError('internal parsing error')

            flush_data()
        finally:
            if end_tokens is not None:
                self._end_token_stack.pop()

        return body
Ejemplo n.º 7
0
    def _parse_blocktrans(self, parser, lineno):
        with_vars = {}
        count = None
        context = None
        trimmed = False
        as_var = None

        if parser.stream.skip_if('name:trimmed'):
            trimmed = True

        if parser.stream.skip_if('name:asvar'):
            as_var = parser.stream.expect(lexer.TOKEN_NAME)
            as_var = nodes.Name(as_var.value, 'store', lineno=as_var.lineno)

        if parser.stream.skip_if('name:with'):
            while parser.stream.look().type == lexer.TOKEN_ASSIGN:
                token = parser.stream.expect(lexer.TOKEN_NAME)
                key = token.value
                next(parser.stream)
                with_vars[key] = parser.parse_expression(False)

        if parser.stream.skip_if('name:count'):
            name = parser.stream.expect(lexer.TOKEN_NAME).value
            parser.stream.expect(lexer.TOKEN_ASSIGN)
            value = parser.parse_expression(False)
            count = (name, value)

        if parser.stream.skip_if('name:context'):
            context = parser.stream.expect(lexer.TOKEN_STRING).value

        parser.stream.expect(lexer.TOKEN_BLOCK_END)

        body_singular = None
        body = []
        additional_vars = set()
        for token in parser.stream:
            if token is lexer.TOKEN_EOF:
                parser.fail(
                    'unexpected end of template, expected endblocktrans tag')
            if token.type is lexer.TOKEN_DATA:
                body.append(token.value)
            elif token.type is lexer.TOKEN_VARIABLE_BEGIN:
                name = parser.stream.expect(lexer.TOKEN_NAME).value
                if name not in with_vars and (count is None
                                              or count[0] != name):
                    additional_vars.add(name)
                parser.stream.expect(lexer.TOKEN_VARIABLE_END)
                # django converts variables inside the blocktrans tag into
                # "%(var_name)s" format, so we do the same.
                body.append('%({})s'.format(name))
            elif token.type is lexer.TOKEN_BLOCK_BEGIN:
                if body_singular is None and parser.stream.skip_if(
                        'name:plural'):
                    if count is None:
                        parser.fail('used plural without specifying count')
                    parser.stream.expect(lexer.TOKEN_BLOCK_END)
                    body_singular = body
                    body = []
                else:
                    parser.stream.expect('name:endblocktrans')
                    break

        if count is not None and body_singular is None:
            parser.fail('plural form not found')

        trans_vars = [
            nodes.Pair(nodes.Const(key), val, lineno=lineno)
            for key, val in with_vars.items()
        ]

        if count is not None:
            trans_vars.append(
                nodes.Pair(nodes.Const(count[0]), count[1], lineno=lineno))

        trans_vars.extend(
            nodes.Pair(nodes.Const(key),
                       nodes.Name(key, 'load', lineno=lineno),
                       lineno=lineno) for key in additional_vars)

        kwargs = [
            nodes.Keyword('trans_vars',
                          nodes.Dict(trans_vars, lineno=lineno),
                          lineno=lineno)
        ]

        if context is not None:
            kwargs.append(
                nodes.Keyword('context',
                              nodes.Const(context, lineno=lineno),
                              lineno=lineno))
        if count is not None:
            kwargs.append(
                nodes.Keyword('count_var',
                              nodes.Const(count[0], lineno=lineno),
                              lineno=lineno))

        body = ''.join(body)
        if trimmed:
            body = ' '.join(map(lambda s: s.strip(),
                                body.strip().splitlines()))

        if body_singular is not None:
            body_singular = ''.join(body_singular)
            if trimmed:
                body_singular = ' '.join(
                    map(lambda s: s.strip(),
                        body_singular.strip().splitlines()))

        if body_singular is None:
            args = []
        else:
            args = [nodes.TemplateData(body_singular, lineno=lineno)]
        args.append(nodes.TemplateData(body, lineno=lineno))
        call = nodes.MarkSafe(self.call_method('_make_blocktrans', args,
                                               kwargs),
                              lineno=lineno)

        if as_var is None:
            return nodes.Output([call], lineno=lineno)
        else:
            return nodes.Assign(as_var, call)
Ejemplo n.º 8
0
def test_complex():
    title_block = nodes.Block(
        "title", [nodes.Output([nodes.TemplateData(u"Page Title")])], False)

    render_title_macro = nodes.Macro(
        "render_title",
        [nodes.Name("title", "param")],
        [],
        [
            nodes.Output([
                nodes.TemplateData(u'\n  <div class="title">\n    <h1>'),
                nodes.Name("title", "load"),
                nodes.TemplateData(u"</h1>\n    <p>"),
                nodes.Name("subtitle", "load"),
                nodes.TemplateData(u"</p>\n    "),
            ]),
            nodes.Assign(nodes.Name("subtitle", "store"),
                         nodes.Const("something else")),
            nodes.Output([
                nodes.TemplateData(u"\n    <p>"),
                nodes.Name("subtitle", "load"),
                nodes.TemplateData(u"</p>\n  </div>\n"),
                nodes.If(
                    nodes.Name("something", "load"),
                    [
                        nodes.Assign(
                            nodes.Name("title_upper", "store"),
                            nodes.Filter(
                                nodes.Name("title", "load"),
                                "upper",
                                [],
                                [],
                                None,
                                None,
                            ),
                        ),
                        nodes.Output([
                            nodes.Name("title_upper", "load"),
                            nodes.Call(
                                nodes.Name("render_title", "load"),
                                [nodes.Const("Aha")],
                                [],
                                None,
                                None,
                            ),
                        ]),
                    ],
                    [],
                    [],
                ),
            ]),
        ],
    )

    for_loop = nodes.For(
        nodes.Name("item", "store"),
        nodes.Name("seq", "load"),
        [
            nodes.Output([
                nodes.TemplateData(u"\n    <li>"),
                nodes.Name("item", "load"),
                nodes.TemplateData(u"</li>\n    <span>"),
            ]),
            nodes.Include(nodes.Const("helper.html"), True, False),
            nodes.Output([nodes.TemplateData(u"</span>\n  ")]),
        ],
        [],
        None,
        False,
    )

    body_block = nodes.Block(
        "body",
        [
            nodes.Output([
                nodes.TemplateData(u"\n  "),
                nodes.Call(
                    nodes.Name("render_title", "load"),
                    [nodes.Name("item", "load")],
                    [],
                    None,
                    None,
                ),
                nodes.TemplateData(u"\n  <ul>\n  "),
            ]),
            for_loop,
            nodes.Output([nodes.TemplateData(u"\n  </ul>\n")]),
        ],
        False,
    )

    tmpl = nodes.Template([
        nodes.Extends(nodes.Const("layout.html")),
        title_block,
        render_title_macro,
        body_block,
    ])

    tmpl_sym = symbols_for_node(tmpl)
    assert tmpl_sym.refs == {
        "render_title": "l_0_render_title",
    }
    assert tmpl_sym.loads == {
        "l_0_render_title": ("undefined", None),
    }
    assert tmpl_sym.stores == set(["render_title"])
    assert tmpl_sym.dump_stores() == {
        "render_title": "l_0_render_title",
    }

    macro_sym = symbols_for_node(render_title_macro, tmpl_sym)
    assert macro_sym.refs == {
        "subtitle": "l_1_subtitle",
        "something": "l_1_something",
        "title": "l_1_title",
        "title_upper": "l_1_title_upper",
    }
    assert macro_sym.loads == {
        "l_1_subtitle": ("resolve", "subtitle"),
        "l_1_something": ("resolve", "something"),
        "l_1_title": ("param", None),
        "l_1_title_upper": ("resolve", "title_upper"),
    }
    assert macro_sym.stores == set(["title", "title_upper", "subtitle"])
    assert macro_sym.find_ref("render_title") == "l_0_render_title"
    assert macro_sym.dump_stores() == {
        "title": "l_1_title",
        "title_upper": "l_1_title_upper",
        "subtitle": "l_1_subtitle",
        "render_title": "l_0_render_title",
    }

    body_sym = symbols_for_node(body_block)
    assert body_sym.refs == {
        "item": "l_0_item",
        "seq": "l_0_seq",
        "render_title": "l_0_render_title",
    }
    assert body_sym.loads == {
        "l_0_item": ("resolve", "item"),
        "l_0_seq": ("resolve", "seq"),
        "l_0_render_title": ("resolve", "render_title"),
    }
    assert body_sym.stores == set([])

    for_sym = symbols_for_node(for_loop, body_sym)
    assert for_sym.refs == {
        "item": "l_1_item",
    }
    assert for_sym.loads == {
        "l_1_item": ("param", None),
    }
    assert for_sym.stores == set(["item"])
    assert for_sym.dump_stores() == {
        "item": "l_1_item",
    }
Ejemplo n.º 9
0
def test_complex():
    title_block = nodes.Block('title', [
        nodes.Output([nodes.TemplateData(u'Page Title')])
    ], False)

    render_title_macro = nodes.Macro('render_title', [nodes.Name('title', 'param')], [], [
        nodes.Output([
            nodes.TemplateData(u'\n  <div class="title">\n    <h1>'),
            nodes.Name('title', 'load'),
            nodes.TemplateData(u'</h1>\n    <p>'),
            nodes.Name('subtitle', 'load'),
            nodes.TemplateData(u'</p>\n    ')]),
        nodes.Assign(
            nodes.Name('subtitle', 'store'), nodes.Const('something else')),
        nodes.Output([
            nodes.TemplateData(u'\n    <p>'),
            nodes.Name('subtitle', 'load'),
            nodes.TemplateData(u'</p>\n  </div>\n'),
            nodes.If(
                nodes.Name('something', 'load'), [
                    nodes.Assign(nodes.Name('title_upper', 'store'),
                                 nodes.Filter(nodes.Name('title', 'load'),
                                              'upper', [], [], None, None)),
                    nodes.Output([
                        nodes.Name('title_upper', 'load'),
                        nodes.Call(nodes.Name('render_title', 'load'), [
                            nodes.Const('Aha')], [], None, None)])], [])])])

    for_loop = nodes.For(
        nodes.Name('item', 'store'),
        nodes.Name('seq', 'load'), [
            nodes.Output([
                nodes.TemplateData(u'\n    <li>'),
                nodes.Name('item', 'load'),
                nodes.TemplateData(u'</li>\n    <span>')]),
            nodes.Include(nodes.Const('helper.html'), True, False),
            nodes.Output([
                nodes.TemplateData(u'</span>\n  ')])], [], None, False)

    body_block = nodes.Block('body', [
        nodes.Output([
            nodes.TemplateData(u'\n  '),
            nodes.Call(nodes.Name('render_title', 'load'), [
                nodes.Name('item', 'load')], [], None, None),
            nodes.TemplateData(u'\n  <ul>\n  ')]),
        for_loop,
        nodes.Output([nodes.TemplateData(u'\n  </ul>\n')])],
        False)

    tmpl = nodes.Template([
        nodes.Extends(nodes.Const('layout.html')),
        title_block,
        render_title_macro,
        body_block,
    ])

    tmpl_sym = symbols_for_node(tmpl)
    assert tmpl_sym.refs == {
        'render_title': 'l_0_render_title',
    }
    assert tmpl_sym.loads == {
        'l_0_render_title': ('undefined', None),
    }
    assert tmpl_sym.stores == set(['render_title'])
    assert tmpl_sym.dump_stores() == {
        'render_title': 'l_0_render_title',
    }

    macro_sym = symbols_for_node(render_title_macro, tmpl_sym)
    assert macro_sym.refs == {
        'subtitle': 'l_1_subtitle',
        'something': 'l_1_something',
        'title': 'l_1_title',
        'title_upper': 'l_1_title_upper',
    }
    assert macro_sym.loads == {
        'l_1_subtitle': ('resolve', 'subtitle'),
        'l_1_something': ('resolve','something'),
        'l_1_title': ('param', None),
        'l_1_title_upper': ('resolve', 'title_upper'),
    }
    assert macro_sym.stores == set(['title', 'title_upper', 'subtitle'])
    assert macro_sym.find_ref('render_title') == 'l_0_render_title'
    assert macro_sym.dump_stores() == {
        'title': 'l_1_title',
        'title_upper': 'l_1_title_upper',
        'subtitle': 'l_1_subtitle',
        'render_title': 'l_0_render_title',
    }

    body_sym = symbols_for_node(body_block)
    assert body_sym.refs == {
        'item': 'l_0_item',
        'seq': 'l_0_seq',
        'render_title': 'l_0_render_title',
    }
    assert body_sym.loads == {
        'l_0_item': ('resolve', 'item'),
        'l_0_seq': ('resolve', 'seq'),
        'l_0_render_title': ('resolve', 'render_title'),
    }
    assert body_sym.stores == set([])

    for_sym = symbols_for_node(for_loop, body_sym)
    assert for_sym.refs == {
        'item': 'l_1_item',
    }
    assert for_sym.loads == {
        'l_1_item': ('param', None),
    }
    assert for_sym.stores == set(['item'])
    assert for_sym.dump_stores() == {
        'item': 'l_1_item',
    }
Ejemplo n.º 10
0
 def make_close_div(self):
     return nodes.TemplateData("</div>")
Ejemplo n.º 11
0
 def make_open_div(self, id):
     return nodes.TemplateData("<div id=\"" + id + "\">")