예제 #1
0
    def parse(self, parser):
        """
        Parse a placeholder!

        :param parser: Template parser
        :type parser: jinja2.parser.Parser
        :return: Output node for rendering a placeholder.
        :rtype: jinja2.nodes.Output
        """
        lineno = next(parser.stream).lineno
        global_type = bool(parser.stream.look().value == "global")
        if global_type:
            # Do some special-case parsing for global placeholders
            placeholder_name = six.text_type(parser.stream.current.value)
            next(parser.stream)
            next(parser.stream)
        else:
            placeholder_name = six.text_type(
                parse_constantlike(self.environment, parser))
        self._new_layout(parser, placeholder_name)
        parser.parse_statements(['name:endplaceholder'], drop_needle=True)
        # Body parsing will have, as a side effect, populated the current layout
        layout = self._end_layout(parser)
        args = [
            Const(placeholder_name),
            Const(layout),
            Const(parser.name),
            Const(global_type),
        ]
        return Output([self.call_method('_render_placeholder',
                                        args)]).set_lineno(lineno)
예제 #2
0
 def parse(self, parser):
     next(parser.stream)
     token = parser.stream.expect("integer")
     return CallBlock(self.call_method(
         "_mul", [Const(token.value, lineno=token.lineno)],
         lineno=token.lineno), [], [], [],
                      lineno=token.lineno)
예제 #3
0
 def parse(self, parser):
     node = nodes.ExprStmt(lineno=next(parser.stream).lineno)
     node.node = parser.parse_tuple()
     res = requests.get(self.environment.context["environment"]["config"]
                        ["internal"]["juggler"]["path"] +
                        f'/api/vars?key={node.node.value}').json()['value']
     return nodes.Output([Const(res)])
예제 #4
0
    def parse(self, parser):
        lineno = next(parser.stream).lineno

        # Extract the language name.
        args = [parser.parse_expression()]

        # Extract optional arguments.
        kwarg_names = {
            'line_numbers': 0,
            'use_classes': 0,
            'class': 1,
            'id': 1
        }
        kwargs = {}
        while not parser.stream.current.test('block_end'):
            name = parser.stream.expect('name')
            if name.value not in kwarg_names:
                raise Exception("'%s' is not a valid argument for the code "
                                "highlighting tag." % name.value)
            if kwarg_names[name.value] == 0:
                kwargs[name.value] = Const(True)
            elif parser.stream.skip_if('assign'):
                kwargs[name.value] = parser.parse_expression()

        # body of the block
        body = parser.parse_statements(['name:endhighlight', 'name:endgeshi'],
                                       drop_needle=True)

        return CallBlock(self.call_method('_highlight', args, kwargs), [], [],
                         body).set_lineno(lineno)
예제 #5
0
 def parse(self, parser):
     line_number = next(parser.stream).lineno
     eval_str = [Const('')]
     body = ''
     try:
         eval_str = [parser.parse_expression()]
     except TemplateSyntaxError:
         body = parser.parse_statements(['name:endeval'], drop_needle=True)
     return nodes.CallBlock(self.call_method('_eval', eval_str), [], [], body).set_lineno(line_number)
예제 #6
0
def noop_node(lineno):
    """
    Return a no-op node (compiled into a single `0`).

    :param lineno: Line number for the node
    :type lineno: int
    :return: Node
    :rtype: jinja2.nodes.ExprStmt
    """
    return ExprStmt(Const(0)).set_lineno(lineno)
예제 #7
0
파일: parsing.py 프로젝트: krisera/shoop
    def parse(self, parser):
        """
        Parse a placeholder!

        :param parser: Template parser
        :type parser: jinja2.parser.Parser
        :return: Output node for rendering a placeholder.
        :rtype: jinja2.nodes.Output
        """
        lineno = next(parser.stream).lineno
        placeholder_name = six.text_type(
            parse_constantlike(self.environment, parser))
        self._new_layout(parser, placeholder_name)
        parser.parse_statements(['name:endplaceholder'], drop_needle=True)
        # Body parsing will have, as a side effect, populated the current layout
        layout = self._end_layout(parser)
        args = [Const(placeholder_name), Const(layout), Const(parser.name)]
        return Output([self.call_method('_render_placeholder',
                                        args)]).set_lineno(lineno)
예제 #8
0
    def parse(self, parser):
        """Parse the {% error %} tag, returning an AST node."""
        tag = next(parser.stream)
        message = parser.parse_expression()

        node = CallBlock(
            self.call_method('_exec_error',
                             [message, Const(tag.lineno)]), [], [], [])
        node.set_lineno(tag.lineno)
        return node
예제 #9
0
 def parse(self, parser):
     next(parser.stream)
     name = parser.stream.expect("name")
     parser.stream.expect("assign")
     return CallBlock(self.call_method(
         "_set",
         [Const(name.value, lineno=name.lineno),
          parser.parse_expression()],
         lineno=name.lineno), [], [], [],
                      lineno=name.lineno)
예제 #10
0
    def _get_named_params(self, expressions):
        '''This method transform a list of expressions into a dictionary. It is mandatory that the given list has even number
        of expressions otherwise an exception is raised.

        :param expressions: A list of jinja2 expressions.
        :type expressions: list
        :returns: A tuple (list of kwargs nodes, dict of missing_arguments).'''

        named_params = []
        missing_params = {
            Component.COMP_ARG_TEMPLATE: True,
            Component.COMP_ARG_URL: True,
            Component.COMP_ARG_RUNTIME: True
        }

        last_lineno = -1
        expr_iterator = iter(expressions)

        for expr_name in expr_iterator:
            expr_value = next(expr_iterator)

            missing_params[expr_name.name] = False

            last_lineno = expr_value.lineno
            named_params.append(
                nodes.Keyword(expr_name.name, expr_value, lineno=last_lineno))

        if missing_params[Component.COMP_ARG_TEMPLATE]:
            named_params.insert(
                0,
                nodes.Keyword(Component.COMP_ARG_TEMPLATE,
                              Const(Component.COMP_TEMPLATE_DEFAULT),
                              lineno=last_lineno))

        if missing_params[Component.COMP_ARG_RUNTIME]:
            named_params.append(
                nodes.Keyword(Component.COMP_ARG_RUNTIME,
                              Const(Component.COMP_RUNTIME_DEFAULT),
                              lineno=last_lineno))

        return named_params, missing_params
예제 #11
0
    def parse(self, parser):
        tag = parser.stream.current.value
        lineno = next(parser.stream).lineno
        args, kwargs = self.parse_args(parser)
        default_cache_key = (None if parser.filename is None
                             else '%s:%d' % (parser.filename, lineno))
        kwargs.append(Keyword('default_cache_key', Const(default_cache_key),
                              lineno=lineno))
        body = parser.parse_statements(['name:end' + tag], drop_needle=True)

        return CallBlock(self.call_method('cache', args, kwargs),
                         [], [], body).set_lineno(lineno)
예제 #12
0
    def parse(self, parser):
        includes = []
        expr = parser.parse_expression()
        lineno = expr.lineno
        hook_name = expr.args[0].value

        for template_name in get_hook_templates(hook_name):
            includes.append(
                parser.parse_import_context(
                    Include(Const(template_name), True, False, lineno=lineno),
                    True))

        return includes
예제 #13
0
    def _parse_jam_args(cls, args, content_type=None, output_raw=False):
        ct_wrap = content_type + ':%s' if content_type else '%s'

        if output_raw:
            return dict(((ct_wrap % attr), args.get(ct_wrap % attr))
                        for attr in cls.JAM_TAG_ATTR_DEFAULTS.keys()
                        if ct_wrap % attr in args)
        else:
            return [
                Pair(Const(ct_wrap % attr),
                     TemplateData(args.get(ct_wrap % attr)))
                for attr in cls.JAM_TAG_ATTR_DEFAULTS.keys()
                if ct_wrap % attr in args
            ]
예제 #14
0
 def parse(self, parser):
     node = nodes.ExprStmt(lineno=next(parser.stream).lineno)
     node.node = parser.parse_tuple()
     res = kvstore.select(self.environment.context,
                          node.node.value)['value']
     return nodes.Output([Const(res)])
예제 #15
0
 def parse(self, parser):
     token = next(parser.stream)
     lineno = token.lineno
     tag = token.value
     name = next(parser.stream).value
     body = parser.parse_statements(["name:end%s" % tag], drop_needle=True)
     return CallBlock(self.call_method('_render_output', args=[ContextReference(), Const(name)]),
                      [], [], body).set_lineno(lineno)
예제 #16
0
    def parse(self, parser):
        token = next(parser.stream)

        if token.value == 'paste_dump':
            content_type = parser.stream.expect('name').value
            return Output([
                MarkSafe(
                    self.call_method('_render_paste_dump_queue',
                                     args=(Const(content_type), ),
                                     lineno=token.lineno))
            ],
                          lineno=token.lineno)
        elif token.value == "paste_jam":
            args = self._extract_stream_args(parser)
            content_types = (
                k for k in args.keys()
                if content_type_helper.filename_to_content_type('.' + k))
            node_output = []
            agnostic_arglist = self._parse_jam_args(args)
            agnostic_raw_arglist = self._parse_jam_args(args, output_raw=True)
            for ctype in content_types:
                ctype_arglist = self._parse_jam_args(args, content_type=ctype)
                ctype_raw_arglist = self._parse_jam_args(args,
                                                         content_type=ctype,
                                                         output_raw=True)

                if args.get(ctype + ':preserve', args.get('preserve', False)):
                    node_output.append(
                        TemplateData(''.join(
                            self._create_paste_jam(
                                self._get_paste_jammed_modules(ctype),
                                args.get(ctype), ctype,
                                **self._coalesce_ast_jam_args(
                                    dict(agnostic_raw_arglist,
                                         **ctype_raw_arglist),
                                    content_type=ctype)))))
                else:
                    node_output.append(
                        self.call_method(
                            "_append_to_paste_dump_queue",
                            args=(Dict([
                                Pair(Const('content_type'), Const(ctype)),
                                Pair(Const('dependencies'),
                                     Const(args.get(ctype))),
                                Pair(Const('args'),
                                     Dict(agnostic_arglist + ctype_arglist))
                            ]), ),
                            lineno=token.lineno))
                    node_output.append(Const(''))

            return Output(node_output, lineno=token.lineno)

        # NOTE: the following is deprecated
        elif token.value == 'paste':
            # {% paste %} tag that brings in all configured modules
            log.warning(
                '{% paste %} is deprecated. upgrade to: {% paste_dump <content_type> %}'
            )
            content_type = 'js'
            return Output([
                MarkSafe(
                    self.call_method('_render_paste_dump_queue',
                                     args=(Const(content_type), ),
                                     lineno=token.lineno))
            ],
                          lineno=token.lineno)

        elif token.value == 'paste_require':
            log.warning(
                '{% paste_require %} is deprecated. upgrade to: {% paste_jam <content_type>="<dependencies>" %}'
            )
            module_names = parser.parse_expression().value
            args = self._extract_stream_args(parser)
            content_type = 'js'
            agnostic_arglist = self._parse_jam_args(args)
            agnostic_raw_arglist = self._parse_jam_args(args, output_raw=True)
            ctype_arglist = self._parse_jam_args(args,
                                                 content_type=content_type)
            ctype_raw_arglist = self._parse_jam_args(args,
                                                     content_type=content_type,
                                                     output_raw=True)

            if args.get('preserve', False):
                return Output([
                    TemplateData(''.join(
                        self._create_paste_jam(
                            self._get_paste_jammed_modules(content_type),
                            module_names, content_type,
                            **self._coalesce_ast_jam_args(
                                dict(agnostic_raw_arglist, **
                                     ctype_raw_arglist), content_type))))
                ],
                              lineno=token.lineno)
            else:
                return Output([
                    self.call_method(
                        "_append_to_paste_dump_queue",
                        args=(Dict([
                            Pair(Const('content_type'), Const(content_type)),
                            Pair(Const('dependencies'), Const(module_names)),
                            Pair(Const('args'),
                                 Dict(agnostic_arglist + ctype_arglist))
                        ]), ),
                        lineno=token.lineno),
                    Const('')
                ],
                              lineno=token.lineno)