Python django.template.Variable() Examples

The following are 30 code examples of django.template.Variable(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.template , or try the search function .
Example #1
Source File: crowdataapp_tags.py    From crowdata with MIT License 6 votes vote down vote up
def render(self, context):
        request = context["request"]
        post = getattr(request, "POST", None)
        form = template.Variable(self.value).resolve(context)
        t = get_template("forms/includes/built_form.html")
        context["form"] = form
        form_args = (form, context, post or None)
        form_for_form = FormForForm(*form_args)

        # kind of a hack
        # add the 'data-verify' attribute if the field is marked
        # as a verifiable field
        for i, field in enumerate(form_for_form.form_fields):
            if field.verify:
                form_for_form.fields[field.slug].widget.attrs['data-verify'] = True

            # We give to all the form fields a common class so we can reference 
            # them in the frontend
            fieldAttrs = form_for_form.fields[field.slug].widget.attrs
            fieldAttrs['class'] = fieldAttrs['class']  + ' form-field'

        context["form_for_form"] = form_for_form
        return t.render(context) 
Example #2
Source File: wtforms.py    From RSSNewsGAE with Apache License 2.0 6 votes vote down vote up
def do_form_field(parser, token):
    """
    Render a WTForms form field allowing optional HTML attributes.
    Invocation looks like this:
      {% form_field form.username class="big_text" onclick="alert('hello')" %}
    where form.username is the path to the field value we want.  Any number
    of key="value" arguments are supported. Unquoted values are resolved as
    template variables.
    """
    parts = token.contents.split(' ', 2)
    if len(parts) < 2:
        error_text = '%r tag must have the form field name as the first value, followed by optional key="value" attributes.'
        raise template.TemplateSyntaxError(error_text % parts[0])

    html_attrs = {}
    if len(parts) == 3:
        raw_args = list(args_split(parts[2]))
        if (len(raw_args) % 2) != 0:
            raise template.TemplateSyntaxError('%r tag received the incorrect number of key=value arguments.' % parts[0])
        for x in range(0, len(raw_args), 2):
            html_attrs[str(raw_args[x])] = Variable(raw_args[x + 1])

    return FormFieldNode(parts[1], html_attrs) 
Example #3
Source File: widget_tweaks_extras.py    From Bitpoll with GNU General Public License v3.0 6 votes vote down vote up
def render(self, context):
        bounded_field = template.Variable(self.field).resolve(context)
        field = bounded_field.field.fields[self.index]
        widget = bounded_field.field.widget.widgets[self.index]

        attrs = widget.attrs.copy()
        print(attrs)
        for k, v in self.assign_dict.items():
            attrs[k] = v.resolve(context)
        for k, v in self.concat_dict.items():
            attrs[k] = widget.attrs.get(k, '') + ' ' + v.resolve(context)
        if bounded_field.errors:
            attrs['class'] = attrs.get('class', '') + ' error'

        if not bounded_field.form.is_bound:
            data = bounded_field.form.initial.get(bounded_field.name,
                                                  field.initial)
            if callable(data):
                data = data()
            data = bounded_field.field.widget.decompress(data)[self.index]
        else:
            data = bounded_field.data[self.index]
        return widget.render('%s_%d' % (bounded_field.html_name, self.index),
                             data, attrs) 
Example #4
Source File: settings_value.py    From Bitpoll with GNU General Public License v3.0 6 votes vote down vote up
def value_from_settings(parser, token):
    bits = token.split_contents()
    if len(bits) < 2:
        raise TemplateSyntaxError("'%s' takes at least one " \
                                  "argument (settings constant to retrieve)" % bits[0])
    settingsvar = bits[1]
    settingsvar = settingsvar[1:-1] if settingsvar[0] == '"' else settingsvar
    asvar = None
    bits = bits[2:]
    if len(bits) >= 2 and bits[-2] == 'as':
        asvar = bits[-1]
        bits = bits[:-2]
    if len(bits):
        raise TemplateSyntaxError("'value_from_settings' didn't recognise " \
                                  "the arguments '%s'" % ", ".join(bits))
    if settingsvar not in settings.TEMPLATE_ALLOWABLE_SETTINGS_VALUES:
        raise TemplateSyntaxError("The settings Variable %s is not allowed to be acessed" % settingsvar)
    return ValueFromSettings(settingsvar, asvar) 
Example #5
Source File: wtforms.py    From jbox with MIT License 6 votes vote down vote up
def do_form_field(parser, token):
    """
    Render a WTForms form field allowing optional HTML attributes.
    Invocation looks like this:
      {% form_field form.username class="big_text" onclick="alert('hello')" %}
    where form.username is the path to the field value we want.  Any number
    of key="value" arguments are supported. Unquoted values are resolved as
    template variables.
    """
    parts = token.contents.split(' ', 2)
    if len(parts) < 2:
        error_text = '%r tag must have the form field name as the first value, followed by optional key="value" attributes.'
        raise template.TemplateSyntaxError(error_text % parts[0])

    html_attrs = {}
    if len(parts) == 3:
        raw_args = list(args_split(parts[2]))
        if (len(raw_args) % 2) != 0:
            raise template.TemplateSyntaxError('%r tag received the incorrect number of key=value arguments.' % parts[0])
        for x in range(0, len(raw_args), 2):
            html_attrs[str(raw_args[x])] = Variable(raw_args[x + 1])

    return FormFieldNode(parts[1], html_attrs) 
Example #6
Source File: wtforms.py    From jbox with MIT License 6 votes vote down vote up
def render(self, context):
        try:
            if '.' in self.field_var:
                base, field_name = self.field_var.rsplit('.', 1)
                field = getattr(Variable(base).resolve(context), field_name)
            else:
                field = context[self.field_var]
        except (template.VariableDoesNotExist, KeyError, AttributeError):
            return settings.TEMPLATE_STRING_IF_INVALID

        h_attrs = {}
        for k, v in iteritems(self.html_attrs):
            try:
                h_attrs[k] = v.resolve(context)
            except template.VariableDoesNotExist:
                h_attrs[k] = settings.TEMPLATE_STRING_IF_INVALID

        return field(**h_attrs) 
Example #7
Source File: wtforms.py    From RSSNewsGAE with Apache License 2.0 6 votes vote down vote up
def render(self, context):
        try:
            if '.' in self.field_var:
                base, field_name = self.field_var.rsplit('.', 1)
                field = getattr(Variable(base).resolve(context), field_name)
            else:
                field = context[self.field_var]
        except (template.VariableDoesNotExist, KeyError, AttributeError):
            return settings.TEMPLATE_STRING_IF_INVALID

        h_attrs = {}
        for k, v in iteritems(self.html_attrs):
            try:
                h_attrs[k] = v.resolve(context)
            except template.VariableDoesNotExist:
                h_attrs[k] = settings.TEMPLATE_STRING_IF_INVALID

        return field(**h_attrs) 
Example #8
Source File: macros.py    From django-macros with MIT License 6 votes vote down vote up
def render(self, context):

        # add all of the use_macros args into context
        for i, arg in enumerate(self.macro.args):
            try:
                template_variable = self.args[i]
                context[arg] = template_variable.resolve(context)
            except IndexError:
                context[arg] = ""

        # add all of use_macros kwargs into context
        for name, default in self.macro.kwargs.items():
            if name in self.kwargs:
                context[name] = self.kwargs[name].resolve(context)
            else:
                if isinstance(default, template.Variable):
                    # variables must be resolved explicitly,
                    # because otherwise if macro's loaded from
                    # a separate file things will break
                    context[name] = default.resolve(context)
                else:
                    context[name] = default

        # return the nodelist rendered in the adjusted context
        return self.macro.nodelist.render(context) 
Example #9
Source File: macros.py    From django-macros with MIT License 6 votes vote down vote up
def render(self, context):

        # add all of the use_macros args into context
        for i, arg in enumerate(self.macro.args):
            try:
                template_variable = self.args[i]
                context[arg] = template_variable.resolve(context)
            except IndexError:
                context[arg] = ""

        # add all of use_macros kwargs into context
        for name, default in self.macro.kwargs.items():
            if name in self.kwargs:
                context[name] = self.kwargs[name].resolve(context)
            else:
                if isinstance(default, template.Variable):
                    # variables must be resolved explicitly,
                    # because otherwise if macro's loaded from
                    # a separate file things will break
                    context[name] = default.resolve(context)
                else:
                    context[name] = default

        # return the nodelist rendered in the adjusted context
        return self.macro.nodelist.render(context) 
Example #10
Source File: macros.py    From django-macros with MIT License 6 votes vote down vote up
def render(self, context):

        # add all of the use_macros args into context
        for i, arg in enumerate(self.macro.args):
            try:
                template_variable = self.args[i]
                context[arg] = template_variable.resolve(context)
            except IndexError:
                context[arg] = ""

        # add all of use_macros kwargs into context
        for name, default in self.macro.kwargs.items():
            if name in self.kwargs:
                context[name] = self.kwargs[name].resolve(context)
            else:
                if isinstance(default, template.Variable):
                    # variables must be resolved explicitly,
                    # because otherwise if macro's loaded from
                    # a separate file things will break
                    context[name] = default.resolve(context)
                else:
                    context[name] = default

        # return the nodelist rendered in the adjusted context
        return self.macro.nodelist.render(context) 
Example #11
Source File: wtforms.py    From googleapps-message-recall with Apache License 2.0 6 votes vote down vote up
def render(self, context):
        try:
            if '.' in self.field_var:
                base, field_name = self.field_var.rsplit('.', 1)
                field = getattr(Variable(base).resolve(context), field_name)
            else:
                field = context[self.field_var]
        except (template.VariableDoesNotExist, KeyError, AttributeError):
            return settings.TEMPLATE_STRING_IF_INVALID

        h_attrs = {}
        for k, v in iteritems(self.html_attrs):
            try:
                h_attrs[k] = v.resolve(context)
            except template.VariableDoesNotExist:
                h_attrs[k] = settings.TEMPLATE_STRING_IF_INVALID

        return field(**h_attrs) 
Example #12
Source File: wtforms.py    From googleapps-message-recall with Apache License 2.0 6 votes vote down vote up
def do_form_field(parser, token):
    """
    Render a WTForms form field allowing optional HTML attributes.
    Invocation looks like this:
      {% form_field form.username class="big_text" onclick="alert('hello')" %}
    where form.username is the path to the field value we want.  Any number 
    of key="value" arguments are supported. Unquoted values are resolved as
    template variables.
    """
    parts = token.contents.split(' ', 2)
    if len(parts) < 2:
        raise template.TemplateSyntaxError('%r tag must have the form field name as the first value, followed by optional key="value" attributes.' % parts[0])

    html_attrs = {}
    if len(parts) == 3:
        raw_args = list(args_split(parts[2]))
        if (len(raw_args) % 2) != 0:
            raise template.TemplateSyntaxError('%r tag received the incorrect number of key=value arguments.' % parts[0])
        for x in range(0, len(raw_args), 2):
            html_attrs[str(raw_args[x])] = Variable(raw_args[x+1])

    return FormFieldNode(parts[1], html_attrs) 
Example #13
Source File: macros.py    From django-macros with MIT License 6 votes vote down vote up
def render(self, context):

        # add all of the use_macros args into context
        for i, arg in enumerate(self.macro.args):
            try:
                template_variable = self.args[i]
                context[arg] = template_variable.resolve(context)
            except IndexError:
                context[arg] = ""

        # add all of use_macros kwargs into context
        for name, default in self.macro.kwargs.items():
            if name in self.kwargs:
                context[name] = self.kwargs[name].resolve(context)
            else:
                if isinstance(default, template.Variable):
                    # variables must be resolved explicitly,
                    # because otherwise if macro's loaded from
                    # a separate file things will break
                    context[name] = default.resolve(context)
                else:
                    context[name] = default

        # return the nodelist rendered in the adjusted context
        return self.macro.nodelist.render(context) 
Example #14
Source File: macros.py    From django-macros with MIT License 5 votes vote down vote up
def __init__(self, macro, args, kwargs):
        # all the values kwargs and the items in args
        # are by assumption template.Variable instances.
        self.macro = macro
        self.args = args
        self.kwargs = kwargs 
Example #15
Source File: macros.py    From django-macros with MIT License 5 votes vote down vote up
def __init__(self, name, nodelist, args, kwargs):
        # the values in the kwargs dictionary are by
        # assumption instances of template.Variable.
        self.name = name
        self.nodelist = nodelist
        self.args = args
        self.kwargs = kwargs 
Example #16
Source File: macros.py    From django-macros with MIT License 5 votes vote down vote up
def __init__(self, macro, args, kwargs):
        # all the values kwargs and the items in args
        # are by assumption template.Variable instances.
        self.macro = macro
        self.args = args
        self.kwargs = kwargs 
Example #17
Source File: macros.py    From django-macros with MIT License 5 votes vote down vote up
def __init__(self, name, nodelist, args, kwargs):
        # the values in the kwargs dictionary are by
        # assumption instances of template.Variable.
        self.name = name
        self.nodelist = nodelist
        self.args = args
        self.kwargs = kwargs 
Example #18
Source File: cache.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, nodelist, expire_time_var, fragment_name, vary_on):
        self.nodelist = nodelist
        self.expire_time_var = Variable(expire_time_var)
        self.fragment_name = fragment_name
        self.vary_on = vary_on 
Example #19
Source File: follow_tags.py    From django-project with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, obj, tpl=None):
        self.obj = template.Variable(obj)
        self.template = tpl[1:-1] if tpl else 'follow/form.html' 
Example #20
Source File: flatpages.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def __init__(self, context_name, starts_with=None, user=None):
        self.context_name = context_name
        if starts_with:
            self.starts_with = template.Variable(starts_with)
        else:
            self.starts_with = None
        if user:
            self.user = template.Variable(user)
        else:
            self.user = None 
Example #21
Source File: macros.py    From django-macros with MIT License 5 votes vote down vote up
def __init__(self, macro, args, kwargs):
        # all the values kwargs and the items in args
        # are by assumption template.Variable instances.
        self.macro = macro
        self.args = args
        self.kwargs = kwargs 
Example #22
Source File: follow_tags.py    From django-project with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def render(self, context):
        obj = self.obj.resolve(context)
        
        if not self.user:
            try:
                user = context['request'].user
            except KeyError:
                raise template.TemplateSyntaxError('There is no request object in the template context.')
        else:
            user = template.Variable(self.user).resolve(context)
        
        return utils.follow_url(user, obj) 
Example #23
Source File: follow_tags.py    From django-project with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, obj, user=None):
        self.obj = template.Variable(obj)
        self.user = user 
Example #24
Source File: i18n.py    From python with Apache License 2.0 5 votes vote down vote up
def __init__(self, filter_expression, noop, asvar=None,
                 message_context=None):
        self.noop = noop
        self.asvar = asvar
        self.message_context = message_context
        self.filter_expression = filter_expression
        if isinstance(self.filter_expression.var, six.string_types):
            self.filter_expression.var = Variable("'%s'" %
                                                  self.filter_expression.var) 
Example #25
Source File: webcms_nav_tags.py    From django-leonardo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def what(self, page, args, default=None):
        language = args.get('language',False)
        if not language:
            language = settings.LANGUAGES[0][0]
        elif language not in (x[0] for x in settings.LANGUAGES):
            language = template.Variable(language).resolve(self.render_context)

        return _translate_page_into(page, language, default=default) 
Example #26
Source File: test_templatetags.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_render_none_as_context_variable(self):
        """
        Tests that an ImageNode without an image and a context variable name
        renders an empty string and puts None in the context variable
        """
        context = {'image': None, 'image_node': 'fake value'}
        node = ImageNode(Variable('image'), 'original', 'image_node')

        rendered = node.render(context)

        self.assertEqual(rendered, '')
        self.assertIsNone(context['image_node']) 
Example #27
Source File: test_templatetags.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_render_valid_image_as_context_variable(self):
        """
        Tests that an ImageNode with a valid image and a context variable name
        renders an empty string and puts a rendition in the context variable
        """
        context = {'image': self.image, 'image_node': 'fake value'}
        node = ImageNode(Variable('image'), 'original', 'image_node')

        rendered = node.render(context)

        self.assertEqual(rendered, '')
        self.assertIsInstance(context['image_node'], Rendition) 
Example #28
Source File: test_templatetags.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_render_none_to_string(self):
        """
        Tests that an ImageNode without image renders an empty string
        """
        context = {'image': None}
        node = ImageNode(Variable('image'), 'original')

        rendered = node.render(context)

        self.assertEqual(rendered, '') 
Example #29
Source File: test_templatetags.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_render_valid_image_to_string(self):
        """
        Tests that an ImageNode with a valid image renders an img tag
        """
        context = {'image': self.image}
        node = ImageNode(Variable('image'), 'original')

        rendered = node.render(context)

        self.assertIn('<img alt="Test image"', rendered) 
Example #30
Source File: i18n.py    From python2017 with MIT License 5 votes vote down vote up
def __init__(self, filter_expression, noop, asvar=None,
                 message_context=None):
        self.noop = noop
        self.asvar = asvar
        self.message_context = message_context
        self.filter_expression = filter_expression
        if isinstance(self.filter_expression.var, six.string_types):
            self.filter_expression.var = Variable("'%s'" %
                                                  self.filter_expression.var)