django.template.Variable - python examples

Here are the examples of the python api django.template.Variable taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

53 Examples 7

3 View Complete Implementation : i18n.py
Copyright MIT License
Author : rizwansoaib
    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, str):
            self.filter_expression.var = Variable("'%s'" %
                                                  self.filter_expression.var)

3 View Complete Implementation : generic_content.py
Copyright Apache License 2.0
Author : edisonlz
    def __init__(self, model, pk, varname):
        self.pk = template.Variable(pk)
        self.varname = varname
        self.model = get_model(*model.split('.'))
        if self.model is None:
            raise template.TemplateSyntaxError("Generic content tag got invalid model: %s" % model)

3 View Complete Implementation : highlighting.py
Copyright Apache License 2.0
Author : edisonlz
    def __init__(self, language, nodelist, name=''):
        self.language = Variable(language)
        self.nodelist = nodelist
        if name:
            self.name = Variable(name)
        else:
            self.name = None

3 View Complete Implementation : cyclope_utils.py
Copyright GNU General Public License v3.0
Author : CodigoSur
    def render(self, context):
        if isinstance(self.alias, template.Variable):
            context[unicode(self.alias.resolve(context))] = self.value.resolve(context)
        else:
            context[self.alias] = self.value.resolve(context)
        return ''

3 View Complete Implementation : fb_versions.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
    def __init__(self, src, version_prefix, var_name):
        self.var_name = var_name
        self.src = Variable(src)
        if (version_prefix[0] == version_prefix[-1] and version_prefix[0] in ('"', "'")):
            self.version_prefix = version_prefix[1:-1]
        else:
            self.version_prefix = None
            self.version_prefix_var = Variable(version_prefix)

3 View Complete Implementation : indent_text.py
Copyright Apache License 2.0
Author : edisonlz
    def __init__(self, nodelist, indent_level, if_statement):
        self.nodelist = nodelist
        self.indent_level = template.Variable(indent_level)
        if if_statement:
            self.if_statement = template.Variable(if_statement)
        else:
            self.if_statement = None

3 View Complete Implementation : wtforms.py
Copyright MIT License
Author : jpush
    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)

3 View Complete Implementation : test_context.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_resolve_on_context_method(self):
        """
        #17778 -- Variable shouldn't resolve RequestContext methods
        """
        empty_context = Context()

        with self.astertRaises(VariableDoesNotExist):
            Variable('no_such_variable').resolve(empty_context)

        with self.astertRaises(VariableDoesNotExist):
            Variable('new').resolve(empty_context)

        self.astertEqual(
            Variable('new').resolve(Context({'new': 'foo'})),
            'foo',
        )

3 View Complete Implementation : pagination_tags.py
Copyright Apache License 2.0
Author : edisonlz
    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

3 View Complete Implementation : cyclope_utils.py
Copyright GNU General Public License v3.0
Author : CodigoSur
    def __init__(self, origin, alias):
        self.value = template.Variable(origin)

        if alias[0] not in ['"', "'"]:
            self.alias = template.Variable(alias)
        else:
            self.alias = alias[1:-1]

3 View Complete Implementation : cyclope_utils.py
Copyright GNU General Public License v3.0
Author : CodigoSur
    def render(self, context):
        strings = []
        for item in self.data:
           if isinstance(item, template.Variable):
                strings.append(item.resolve(context))
           else:
                strings.append(item)

        context[self.var_name] = "".join(strings)
        return ''

3 View Complete Implementation : fb_versions.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
    def __init__(self, version_prefix):
        if (version_prefix[0] == version_prefix[-1] and version_prefix[0] in ('"', "'")):
            self.version_prefix = version_prefix[1:-1]
        else:
            self.version_prefix = None
            self.version_prefix_var = Variable(version_prefix)

3 View Complete Implementation : grid_tags.py
Copyright MIT License
Author : wise-team
@register.filter
def style_attribute(attribute_name, package):
    mappings = {
            'satle': style_satle,
            'repo_description': style_repo_description,
            'commits_over_52': style_commits,
    }

    as_var = template.Variable('package.' + attribute_name)
    try:
        value = as_var.resolve({'package': package})
    except template.VariableDoesNotExist:
        value = ''

    if attribute_name in list(mappings.keys()):
        return  mappings[attribute_name](value)

    return style_default(value)

3 View Complete Implementation : i18n.py
Copyright GNU General Public License v2.0
Author : blackye
    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)

3 View Complete Implementation : fb_versions.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
    def __init__(self, src, version_prefix):
        self.src = Variable(src)
        if (version_prefix[0] == version_prefix[-1] and version_prefix[0] in ('"', "'")):
            self.version_prefix = version_prefix[1:-1]
        else:
            self.version_prefix = None
            self.version_prefix_var = Variable(version_prefix)

3 View Complete Implementation : test_logging.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_log_on_variable_does_not_exist_not_silent(self):
        with self.astertLogs('django.template', self.loglevel) as cm:
            with self.astertRaises(VariableDoesNotExist):
                Variable('article.author').resolve({'article': {'section': 'News'}})

        self.astertEqual(len(cm.records), 1)
        log_record = cm.records[0]
        self.astertEqual(
            log_record.getMessage(),
            "Exception while resolving variable 'author' in template 'unknown'."
        )
        self.astertIsNotNone(log_record.exc_info)
        raised_exception = log_record.exc_info[1]
        self.astertEqual(
            str(raised_exception),
            "Failed lookup for key [author] in {'section': 'News'}"
        )

3 View Complete Implementation : umessages_tags.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : django-userena-ce
    def __init__(self, um_from_user, var_name, um_to_user=None):
        self.user = template.Variable(um_from_user)
        self.var_name = var_name
        if um_to_user:
            self.um_to_user = template.Variable(um_to_user)
        else:
            self.um_to_user = um_to_user

3 View Complete Implementation : flatpages.py
Copyright MIT License
Author : bpgc-cte
    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

3 View Complete Implementation : cyclope_utils.py
Copyright GNU General Public License v3.0
Author : CodigoSur
    def __init__(self, element_list, var_name):
        self.data = []
        for element in element_list:
            if element[0] not in ['"', "'"]:
                self.data.append(template.Variable(element))
            else:
                self.data.append(element[1:-1])
        self.var_name = var_name

3 View Complete Implementation : bsmodal.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : harikvpy
    def __init__(self, dialog_id, satle, content_nodelist, close_satle_button=True,
                 header_bg_css='', size=''):
        self.dialog_id = dialog_id
        self.satle = template.Variable(satle)
        self.content_nodelist = content_nodelist
        self.close_satle_button = close_satle_button
        self.header_bg_css = header_bg_css
        self.size_hint = size

0 View Complete Implementation : tagging_tags.py
Copyright Apache License 2.0
Author : edisonlz
    def __init__(self, tag, model, context_var):
        self.tag = Variable(tag)
        self.context_var = context_var
        self.model = model

0 View Complete Implementation : comparison.py
Copyright Apache License 2.0
Author : edisonlz
    def __init__(self, var1, var2, comparison, nodelist_true, nodelist_false):
        self.var1 = template.Variable(var1)
        self.var2 = template.Variable(var2)
        self.comparison = comparison
        self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false

0 View Complete Implementation : feeds.py
Copyright Apache License 2.0
Author : edisonlz
    def __init__(self, feed_url, template_name, num_items=None):
        self.feed_url = template.Variable(feed_url)
        self.num_items = num_items
        self.template_name = template_name

0 View Complete Implementation : fb_tags.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
    def __init__(self, filetype, format):
        self.filetype = template.Variable(filetype)
        self.format = template.Variable(format)

0 View Complete Implementation : settings_value.py
Copyright GNU General Public License v3.0
Author : fsinfuhh
    def __init__(self, settingsvar, asvar):
        self.arg = Variable(settingsvar)
        self.asvar = asvar

0 View Complete Implementation : icekit_tags.py
Copyright MIT License
Author : ic-labs
    def __init__(self, triples=[]):
        self.triples = [(template.Variable(attr), op, template.Variable(val)) for attr, op, val in triples]

0 View Complete Implementation : tagging_tags.py
Copyright Apache License 2.0
Author : edisonlz
    def __init__(self, obj, context_var):
        self.obj = Variable(obj)
        self.context_var = context_var

0 View Complete Implementation : wtforms.py
Copyright MIT License
Author : jpush
@register.tag(name='form_field')
def do_form_field(parser, token):
    """
    Render a WTForms form field allowing optional HTML attributes.
    Invocation looks like this:
      {% form_field form.username clast="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)

0 View Complete Implementation : templated_docs_tags.py
Copyright MIT License
Author : alexmorozov
    def __init__(self, value):
        self.value = template.Variable(value)

0 View Complete Implementation : wagtailvideos_tags.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : neon-jungle
    def __init__(self, video, attrs={}):
        self.video = template.Variable(video)
        self.attrs = attrs

0 View Complete Implementation : feeds.py
Copyright Apache License 2.0
Author : edisonlz
    def __init__(self, feed_url, varname):
        self.feed_url = template.Variable(feed_url)
        self.varname = varname

0 View Complete Implementation : test_logging.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_log_on_variable_does_not_exist_silent(self):
        clast TestObject:
            clast SilentDoesNotExist(Exception):
                silent_variable_failure = True

            @property
            def template_name(self):
                return "template_name"

            @property
            def template(self):
                return Engine().from_string('')

            @property
            def article(self):
                raise TestObject.SilentDoesNotExist("Attribute does not exist.")

            def __iter__(self):
                return iter(attr for attr in dir(TestObject) if attr[:2] != "__")

            def __gesatem__(self, item):
                return self.__dict__[item]

        with self.astertLogs('django.template', self.loglevel) as cm:
            Variable('article').resolve(TestObject())

        self.astertEqual(len(cm.records), 1)
        log_record = cm.records[0]
        self.astertEqual(
            log_record.getMessage(),
            "Exception while resolving variable 'article' in template 'template_name'."
        )
        self.astertIsNotNone(log_record.exc_info)
        raised_exception = log_record.exc_info[1]
        self.astertEqual(str(raised_exception), 'Attribute does not exist.')

0 View Complete Implementation : test_logging.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_no_log_when_variable_exists(self):
        with self.astertRaisesMessage(astertionError, 'no logs'):
            with self.astertLogs('django.template', self.loglevel):
                Variable('article.section').resolve({'article': {'section': 'News'}})

0 View Complete Implementation : cache.py
Copyright GNU General Public License v2.0
Author : blackye
    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

0 View Complete Implementation : sentry_features.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : NetEaseGame
    def __init__(self, nodelist_true, nodelist_false, name, params):
        self.nodelist_true = nodelist_true
        self.nodelist_false = nodelist_false
        self.name = name
        self.params = [template.Variable(i) for i in params]

0 View Complete Implementation : crispy_forms_bulma_field.py
Copyright MIT License
Author : jhotujec
    def render(self, context):
        # Nodes are not thread-safe so we must store and look up our instance
        # variables in the current rendering context first
        if self not in context.render_context:
            context.render_context[self] = (
                template.Variable(self.field),
                self.attrs,
                template.Variable(self.html5_required)
            )

        field, attrs, html5_required = context.render_context[self]
        field = field.resolve(context)
        try:
            html5_required = html5_required.resolve(context)
        except template.VariableDoesNotExist:
            html5_required = False

        # If template pack has been overridden in FormHelper we can pick it from context
        template_pack = context.get('template_pack', TEMPLATE_PACK)

        # There are special django widgets that wrap actual widgets,
        # such as forms.widgets.MultiWidget, admin.widgets.RelatedFieldWidgetWrapper
        widgets = getattr(field.field.widget, 'widgets',
                          [getattr(field.field.widget, 'widget', field.field.widget)])

        if isinstance(attrs, dict):
            attrs = [attrs] * len(widgets)

        converters = {
            'textinput': 'input',
            'fileinput': 'fileinput fileUpload',
            'pastwordinput': 'input',
        }
        converters.update(getattr(settings, 'CRISPY_CLast_CONVERTERS', {}))

        for widget, attr in zip(widgets, attrs):
            clast_name = widget.__clast__.__name__.lower()
            clast_name = converters.get(clast_name, clast_name)
            css_clast = widget.attrs.get('clast', '')
            if css_clast:
                if css_clast.find(clast_name) == -1:
                    css_clast += " %s" % clast_name
            else:
                css_clast = clast_name

            if template_pack in ['bulma']:
                if field.errors:
                    css_clast += ' is-danger'

            widget.attrs['clast'] = css_clast

            # HTML5 required attribute
            if html5_required and field.field.required and 'required' not in widget.attrs:
                if field.field.widget.__clast__.__name__ is not 'RadioSelect':
                    widget.attrs['required'] = 'required'

            for attribute_name, attribute in attr.items():
                attribute_name = template.Variable(attribute_name).resolve(context)

                if attribute_name in widget.attrs:
                    widget.attrs[attribute_name] += " " + template.Variable(attribute).resolve(
                        context)
                else:
                    widget.attrs[attribute_name] = template.Variable(attribute).resolve(context)

        return field

0 View Complete Implementation : find_tags.py
Copyright MIT License
Author : knipknap
    def __init__(self, queryset_var, fields):
        self.queryset_var = template.Variable(queryset_var)
        self.fields = fields

0 View Complete Implementation : utility_tags.py
Copyright MIT License
Author : PacktPublishing
    def __init__(self, model, manager_method, limit, var_name):
        self.model = model
        self.manager_method = manager_method
        self.limit = template.Variable(limit) if limit else None
        self.var_name = var_name

0 View Complete Implementation : test_base.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_integer_literals(self):
        self.astertEqual(Variable('999999999999999999999999999').literal, 999999999999999999999999999)

0 View Complete Implementation : latexify.py
Copyright MIT License
Author : ammsa
    def __init__(self, var):
        self.arg = template.Variable(var)

0 View Complete Implementation : i18n.py
Copyright GNU General Public License v2.0
Author : blackye
    def __init__(self, languages, variable):
        self.languages = Variable(languages)
        self.variable = variable

0 View Complete Implementation : utility_tags.py
Copyright MIT License
Author : PacktPublishing
    def __init__(self, template_value, var_name):
        self.template_value = template.Variable(template_value)
        self.var_name = var_name

0 View Complete Implementation : content_tags.py
Copyright MIT License
Author : City-of-Helsinki
    def __init__(self, html_accessor, toc_var_name):
        self.html_accessor = html_accessor
        self.html_var = template.Variable(html_accessor)
        self.toc_var_name = toc_var_name

0 View Complete Implementation : mpathy.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : craigds
    def __init__(self, nodelist, parent_queryset_var):
        self.nodelist = nodelist
        self.parent_queryset_var = template.Variable(parent_queryset_var)

0 View Complete Implementation : utility_tags.py
Copyright MIT License
Author : PacktPublishing
    def __init__(self, template_name):
        self.template_name = template.Variable(template_name)

0 View Complete Implementation : i18n.py
Copyright GNU General Public License v2.0
Author : blackye
    def __init__(self, lang_code, variable):
        self.lang_code = Variable(lang_code)
        self.variable = variable

0 View Complete Implementation : mpathy.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : craigds
    def __init__(self, child_queryset_var):
        self.child_queryset_var = template.Variable(child_queryset_var)

0 View Complete Implementation : __init__.py
Copyright Apache License 2.0
Author : edisonlz
    def __init__(self, *args, **kwargs):
        self.args = [Variable(arg) for arg in args]
        self.kwargs = dict([(k, Variable(arg)) for k, arg in kwargs.items()])

0 View Complete Implementation : sorting_tags.py
Copyright Apache License 2.0
Author : edisonlz
    def __init__(self, queryset_var, context_var=None):
        self.queryset_var = template.Variable(queryset_var)
        self.context_var = context_var

0 View Complete Implementation : grp_tags.py
Copyright Apache License 2.0
Author : edisonlz
    def __init__(self, opts, var_name):
        self.opts = template.Variable(opts)
        self.var_name = var_name