Пример #1
0
        class Hello(core.Tag):
            options = core.Options(
                arguments.Argument('name', required=False, default='world'),
                'as',
                arguments.Argument('varname', required=False, resolve=False))

            def render_tag(self, context, name, varname):
                output = 'hello %s' % name
                if varname:
                    context[varname] = output
                    return ''
                return output
Пример #2
0
 def test_optional_given(self):
     options = core.Options(
         arguments.Argument('myarg'),
         arguments.Argument('optarg', required=False, default=None),
     )
     dummy_tokens = DummyTokens('myval', 'optval')
     kwargs, blocks = options.parse(dummy_parser, dummy_tokens)
     self.assertEqual(blocks, {})
     self.assertEqual(len(kwargs), 2)
     dummy_context = {}
     self.assertEqual(kwargs['myarg'].resolve(dummy_context), 'myval')
     self.assertEqual(kwargs['optarg'].resolve(dummy_context), 'optval')
Пример #3
0
 def test_partial_breakpoints_both(self):
     options = core.Options(
         arguments.Argument('first'),
         'also',
         'using',
         arguments.Argument('second', required=False),
     )
     # check only using the first breakpoint
     dummy_tokens = DummyTokens('firstval', 'also', 'secondval')
     # should raise an exception
     self.assertRaises(exceptions.BreakpointExpected, options.parse,
                       dummy_parser, dummy_tokens)
Пример #4
0
 def test_06_complex(self):
     """
     test a complex tag option parser
     """
     options = core.Options(
         arguments.Argument('singlearg'),
         arguments.MultiValueArgument('multiarg', required=False),
         'as',
         arguments.Argument('varname', required=False),
         'safe',
         arguments.Flag('safe', true_values=['on', 'true'], default=False)
     )
     # test simple 'all arguments given'
     dummy_tokens = DummyTokens(1, 2, 3, 'as', 4, 'safe', 'true')
     dummy_context = {}
     kwargs, blocks = options.parse(dummy_parser, dummy_tokens)
     self.assertEqual(blocks, {})
     self.assertEqual(len(kwargs), 4)
     expected = [
         ('singlearg', 1),
         ('multiarg', [2, 3]),
         ('varname', 4),
         ('safe', True)
     ]
     for key, value in expected:
         self.assertEqual(kwargs[key].resolve(dummy_context), value)
     # test 'only first argument given'
     dummy_tokens = DummyTokens(1)
     kwargs, blocks = options.parse(dummy_parser, dummy_tokens)
     self.assertEqual(blocks, {})
     self.assertEqual(len(kwargs), 4)
     expected = [
         ('singlearg', 1),
         ('multiarg', []),
         ('varname', None),
         ('safe', False)
     ]
     for key, value in expected:
         self.assertEqual(kwargs[key].resolve(dummy_context), value)
     # test first argument and last argument given
     dummy_tokens = DummyTokens(2, 'safe', 'false')
     kwargs, blocks = options.parse(dummy_parser, dummy_tokens)
     self.assertEqual(blocks, {})
     self.assertEqual(len(kwargs), 4)
     expected = [
         ('singlearg', 2),
         ('multiarg', []),
         ('varname', None),
         ('safe', False)
     ]
     for key, value in expected:
         self.assertEqual(kwargs[key].resolve(dummy_context), value)
Пример #5
0
 def test_breakpoints_not_enough_arguments(self):
     """
     Test parsing with breakpoints
     """
     options = core.Options(
         arguments.Argument('myarg'),
         'as',
         arguments.Argument('varname'),
         'using',
         arguments.Argument('using'),
     )
     dummy_tokens = DummyTokens('myval')
     self.assertRaises(exceptions.ArgumentRequiredError, options.parse,
                       dummy_parser, dummy_tokens)
Пример #6
0
 def test_optional_firstonly(self):
     options = core.Options(
         arguments.Argument('first'),
         'also',
         'using',
         arguments.Argument('second', required=False),
     )
     # check only using the first argument
     dummy_tokens = DummyTokens('firstval')
     kwargs, blocks = options.parse(dummy_parser, dummy_tokens)
     self.assertEqual(blocks, {})
     self.assertEqual(len(kwargs), 2)
     dummy_context = {}
     self.assertEqual(kwargs['first'].resolve(dummy_context), 'firstval')
     self.assertEqual(kwargs['second'].resolve(dummy_context), None)
Пример #7
0
        class SuppressException(helpers.AsTag):
            options = core.Options(
                arguments.Argument('name'),
                'as',
                arguments.Argument('var', resolve=False, required=False),
            )

            def get_value(self, context, name):
                raise MyException(name)

            def get_value_for_context(self, context, name):
                try:
                    return self.get_value(context, name)
                except MyException:
                    return message
Пример #8
0
 def test_optional_both(self):
     options = core.Options(
         arguments.Argument('first'),
         'also',
         'using',
         arguments.Argument('second', required=False),
     )
     # check using both arguments and both breakpoints
     dummy_tokens = DummyTokens('firstval', 'also', 'using', 'secondval')
     kwargs, blocks = options.parse(dummy_parser, dummy_tokens)
     self.assertEqual(blocks, {})
     self.assertEqual(len(kwargs), 2)
     dummy_context = {}
     self.assertEqual(kwargs['first'].resolve(dummy_context), 'firstval')
     self.assertEqual(kwargs['second'].resolve(dummy_context), 'secondval')
Пример #9
0
 def test_complex_only_first_argument(self):
     options = core.Options(
         arguments.Argument('singlearg'),
         arguments.MultiValueArgument('multiarg', required=False), 'as',
         arguments.Argument('varname', required=False), 'safe',
         arguments.Flag('safe', true_values=['on', 'true'], default=False))
     # test 'only first argument given'
     dummy_tokens = DummyTokens(1)
     dummy_context = {}
     kwargs, blocks = options.parse(dummy_parser, dummy_tokens)
     self.assertEqual(blocks, {})
     self.assertEqual(len(kwargs), 4)
     expected = [('singlearg', 1), ('multiarg', []), ('varname', None),
                 ('safe', False)]
     for key, value in expected:
         self.assertEqual(kwargs[key].resolve(dummy_context), value)
Пример #10
0
class With(core.Tag):
    name = 'ct_with'

    options = core.Options(
        arguments.Argument('value'),
        'as',
        arguments.Argument('varname', resolve=False),
        blocks=['endwith'],
    )

    def render_tag(self, context, value, varname, endwith):
        context.push()
        context[varname] = value
        output = endwith.render(context)
        context.pop()
        return output
Пример #11
0
        class Inc(helpers.InclusionTag):
            template = 'test.html'

            options = core.Options(arguments.Argument('var'), )

            def get_context(self, context, var):
                return {'var': var}
Пример #12
0
 def test_breakpoint_okay(self):
     options = core.Options(
         arguments.Argument('myarg'),
         'as',
         arguments.Argument('varname'),
         'using',
         arguments.Argument('using'),
     )
     dummy_tokens = DummyTokens('myval', 'as', 'myname', 'using',
                                'something')
     kwargs, blocks = options.parse(dummy_parser, dummy_tokens)
     self.assertEqual(blocks, {})
     self.assertEqual(len(kwargs), 3)
     dummy_context = {}
     self.assertEqual(kwargs['myarg'].resolve(dummy_context), 'myval')
     self.assertEqual(kwargs['varname'].resolve(dummy_context), 'myname')
     self.assertEqual(kwargs['using'].resolve(dummy_context), 'something')
Пример #13
0
        class Dummy(helpers.AsTag):
            options = core.Options(
                'as',
                arguments.Argument('varname', resolve=False, required=False),
            )

            def get_value(self, context):
                return "dummy"
Пример #14
0
        class IncPollute(helpers.InclusionTag):
            template = 'test.html'

            options = core.Options(arguments.Argument('var'))

            def get_context(self, context, var):
                context.update({'var': 'polluted'})
                return context
Пример #15
0
class For(core.Tag):
    name = 'ct_for'
    
    options = core.Options(
        CommaSeperatableMultiValueArgument('loopvars', resolve=False),
        'in',
        arguments.Argument('values'),
        blocks=[('empty', 'pre_empty'), ('endfor', 'post_empty')],
    )
    
    def render_tag(self, context, loopvars, values, pre_empty, post_empty):
        if 'forloop' in context:
            parentloop = context['forloop']
        else:
            parentloop = {}
        context.push()
        if not hasattr(values, '__len__'):
            values = list(values)
        len_values = len(values)
        if len_values < 1:
            context.pop()
            return post_empty.render(context)
        nodelist = template.NodeList()
        unpack = len(loopvars) > 1
        # Create a forloop value in the context.  We'll update counters on each
        # iteration just below.
        loop_dict = context['forloop'] = {'parentloop': parentloop}
        for i, item in enumerate(values):
            # Shortcuts for current loop iteration number.
            loop_dict['counter0'] = i
            loop_dict['counter'] = i+1
            # Reverse counter iteration numbers.
            loop_dict['revcounter'] = len_values - i
            loop_dict['revcounter0'] = len_values - i - 1
            # Boolean values designating first and last times through loop.
            loop_dict['first'] = (i == 0)
            loop_dict['last'] = (i == len_values - 1)

            if unpack:
                # If there are multiple loop variables, unpack the item into
                # them.
                context.update(dict(zip(loopvars, item)))
            else:
                context[loopvars[0]] = item
            for node in pre_empty:
                nodelist.append(node.render(context))
            if unpack:
                # The loop variables were pushed on to the context so pop them
                # off again. This is necessary because the tag lets the length
                # of loopvars differ to the length of each set of items and we
                # don't want to leave any vars from the previous loop on the
                # context.
                context.pop()
        context.pop()
        return nodelist.render(context)
Пример #16
0
 def test_simple_parsing(self):
     """
     Test very basic single argument parsing
     """
     options = core.Options(arguments.Argument('myarg'), )
     dummy_tokens = DummyTokens('myval')
     kwargs, blocks = options.parse(dummy_parser, dummy_tokens)
     self.assertEqual(blocks, {})
     self.assertEqual(len(kwargs), 1)
     dummy_context = {}
     self.assertEqual(kwargs['myarg'].resolve(dummy_context), 'myval')
Пример #17
0
class Now(core.Tag):
    name = 'ct_now'
    
    options = core.Options(
        arguments.Argument('format_string'),
    )

    def render_tag(self, context, format_string):
        from datetime import datetime
        from django.utils.dateformat import DateFormat
        df = DateFormat(datetime.now())
        return df.format(format_string)
Пример #18
0
        class StartBlock(core.Tag):
            options = core.Options(arguments.Argument("myarg", resolve=False),
                                   blocks=[
                                       BlockDefinition(
                                           "nodelist",
                                           VariableBlockName(
                                               "end_block %(value)s", 'myarg'),
                                           "end_block")
                                   ])

            def render_tag(self, context, myarg, nodelist):
                return "nodelist:%s;myarg:%s" % (nodelist.render(context),
                                                 myarg)
Пример #19
0
        class Cycle(core.Tag):
            name = 'classy_cycle'

            options = core.Options(
                arguments.MultiValueArgument('values'),
                'as',
                arguments.Argument('varname', required=False, resolve=False),
            )

            def render_tag(self, context, values, varname):
                if self not in context.render_context:
                    context.render_context[self] = itertools_cycle(values)
                cycle_iter = context.render_context[self]
                value = cycle_iter.next()
                if varname:
                    context[varname] = value
                return value
Пример #20
0
 class Fail4(helpers.AsTag):
     options = core.Options(
         'as',
         arguments.Argument('varname', resolve=False),
     )
Пример #21
0
 def test_simple_parsing_too_many_arguments(self):
     options = core.Options(arguments.Argument('myarg'), )
     dummy_tokens = DummyTokens('myval', 'myval2')
     self.assertRaises(exceptions.TooManyArguments, options.parse,
                       dummy_parser, dummy_tokens)