Python django.template.Variable() Examples

The following are 30 code examples for showing how to use django.template.Variable(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.template , or try the search function .

Example 1
Project: crowdata   Author: crowdata   File: crowdataapp_tags.py    License: 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
Project: jbox   Author: jpush   File: wtforms.py    License: 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 3
Project: jbox   Author: jpush   File: wtforms.py    License: 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 4
Project: RSSNewsGAE   Author: liantian-cn   File: wtforms.py    License: 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 5
Project: RSSNewsGAE   Author: liantian-cn   File: wtforms.py    License: 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 6
Project: googleapps-message-recall   Author: google   File: wtforms.py    License: 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 7
Project: googleapps-message-recall   Author: google   File: wtforms.py    License: 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 8
Project: Bitpoll   Author: fsinfuhh   File: settings_value.py    License: 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 9
Project: Bitpoll   Author: fsinfuhh   File: widget_tweaks_extras.py    License: 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 10
Project: django-macros   Author: nalourie   File: macros.py    License: 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
Project: django-macros   Author: nalourie   File: macros.py    License: 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 12
Project: django-macros   Author: nalourie   File: macros.py    License: 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 13
Project: django-macros   Author: nalourie   File: macros.py    License: 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
Project: django-accounting   Author: dulacp   File: form_tags.py    License: MIT License 5 votes vote down vote up
def __init__(self, field_str):
        self.field = template.Variable(field_str) 
Example 15
Project: donation-tracker   Author: GamesDoneQuick   File: donation_tags.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, tag, page='request.GET.page'):
        self.tag = tag
        self.page = template.Variable(page) 
Example 16
Project: donation-tracker   Author: GamesDoneQuick   File: donation_tags.py    License: Apache License 2.0 5 votes vote down vote up
def render(self, context):
        sort = tryresolve(template.Variable('request.GET.sort'), context)
        order = tryresolve(template.Variable('request.GET.order'), context)
        if self.tag == 'pagefirst':
            return sortlink('first', '|< ', sort=sort, order=order, page=1)
        elif self.tag == 'pagelast':
            page = self.page.resolve(context)
            return sortlink('last', '>| ', sort=sort, order=order, page=page)
        elif self.tag == 'pagefull':
            return sortlink(None, 'View Full List', sort=sort, order=order, page='full') 
Example 17
Project: donation-tracker   Author: GamesDoneQuick   File: donation_tags.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, tag, page):
        self.tag = tag
        self.page = template.Variable(page) 
Example 18
Project: donation-tracker   Author: GamesDoneQuick   File: donation_tags.py    License: Apache License 2.0 5 votes vote down vote up
def render(self, context):
        sort = tryresolve(template.Variable('request.GET.sort'), context)
        order = tryresolve(template.Variable('request.GET.order'), context)
        page = self.page.resolve(context)
        return sortlink(
            self.tag[4:], PagePNNode.dc[self.tag], sort=sort, order=order, page=page
        ) 
Example 19
Project: donation-tracker   Author: GamesDoneQuick   File: donation_tags.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, tag, page):
        self.tag = tag
        self.page = template.Variable(page) 
Example 20
Project: donation-tracker   Author: GamesDoneQuick   File: donation_tags.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, time):
        self.time = template.Variable(time) 
Example 21
Project: coursys   Author: sfu-fas   File: course_display.py    License: GNU General Public License v3.0 5 votes vote down vote up
def hash(object, attr):
    pseudo_context = { 'object' : object }
    try:
        value = Variable('object.%s' % attr).resolve(pseudo_context)
    except VariableDoesNotExist:
        value = None
    return value 
Example 22
Project: coursys   Author: sfu-fas   File: grade_student.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, dictionary, aslug, userid):
        self.dictionary = template.Variable(dictionary)
        self.aslug = template.Variable(aslug)
        self.userid = template.Variable(userid) 
Example 23
Project: coursys   Author: sfu-fas   File: event_display.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, handler, action, editor, person, varname):
        self.handler = template.Variable(handler)
        self.editor = template.Variable(editor)
        self.person = template.Variable(person)
        self.action = action
        self.varname = varname 
Example 24
Project: coursys   Author: sfu-fas   File: sims_check.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, obj):
        self.obj = template.Variable(obj)
        #self.user = template.Variable('user') 
Example 25
Project: ideascube   Author: ideascube   File: ideascube_tags.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def is_in_qs(context, key, value):
    req = template.Variable('request').resolve(context)
    return _is_in_qs(req.GET.copy(), key, value) 
Example 26
Project: ideascube   Author: ideascube   File: ideascube_tags.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def add_qs(context, **kwargs):
    req = template.Variable('request').resolve(context)
    params = _add_qs(req.GET.copy(), **kwargs)
    return '?%s' % params.urlencode() 
Example 27
Project: ideascube   Author: ideascube   File: ideascube_tags.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def replace_qs(context, **kwargs):
    req = template.Variable('request').resolve(context)
    params = _replace_qs(req.GET.copy(), **kwargs)
    return '?%s' % params.urlencode() 
Example 28
Project: ideascube   Author: ideascube   File: ideascube_tags.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def remove_qs(context, **kwargs):
    req = template.Variable('request').resolve(context)
    params = _remove_qs(req.GET.copy(), **kwargs)
    return '?%s' % params.urlencode() 
Example 29
Project: mendelmd   Author: raonyguimaraes   File: pagination_tags.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, queryset_var, paginate_by=DEFAULT_PAGINATION,
        orphans=DEFAULT_ORPHANS, context_var=None):
        self.queryset_var = template.Variable(queryset_var)
        if isinstance(paginate_by, int):
            self.paginate_by = paginate_by
        else:
            self.paginate_by = template.Variable(paginate_by)
        self.orphans = orphans
        self.context_var = context_var 
Example 30
Project: mendelmd   Author: raonyguimaraes   File: pagination_tags.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, queryset_var, paginate_by=DEFAULT_PAGINATION,
        orphans=DEFAULT_ORPHANS, context_var=None):
        self.queryset_var = template.Variable(queryset_var)
        if isinstance(paginate_by, int):
            self.paginate_by = paginate_by
        else:
            self.paginate_by = template.Variable(paginate_by)
        self.orphans = orphans
        self.context_var = context_var