class Variable

from django.template.base import Variable
A template variable, resolvable against a given context. The variable may
be a hard-coded string (if it begins and ends with single or double quote
marks)::

    >>> c = {'article': {'section':'News'}}
    >>> Variable('article.section').resolve(c)
    'News'
    >>> Variable('article').resolve(c)
    {'section': 'News'}
    >>> class AClass: pass
    >>> c = AClass()
    >>> c.article = AClass()
    >>> c.article.section = 'News'

(The example assumes VARIABLE_ATTRIBUTE_SEPARATOR is '.')

Ancestors (MRO)

  1. builtins.object
  2. django.template.base.Variable
AttributeTypeDefined in
def __init__(self, var)
django.template.base.Variable
Initialize self.  See help(type(self)) for accurate signature.
    def __init__(self, var):
        self.var = var
        self.literal = None
        self.lookups = None
        self.translate = False
        self.message_context = None

        if not isinstance(var, str):
            raise TypeError("Variable must be a string or number, got %s" % type(var))
        try:
            # First try to treat this variable as a number.
            #
            # Note that this could cause an OverflowError here that we're not
            # catching. Since this should only happen at compile time, that's
            # probably OK.

            # Try to interpret values containing a period or an 'e'/'E'
            # (possibly scientific notation) as a float;  otherwise, try int.
            if "." in var or "e" in var.lower():
                self.literal = float(var)
                # "2." is invalid
                if var[-1] == ".":
                    raise ValueError
            else:
                self.literal = int(var)
        except ValueError:
            # A ValueError means that the variable isn't a number.
            if var[0:2] == "_(" and var[-1] == ")":
                # The result of the lookup should be translated at rendering
                # time.
                self.translate = True
                var = var[2:-1]
            # If it's wrapped with quotes (single or double), then
            # we're also dealing with a literal.
            try:
                self.literal = mark_safe(unescape_string_literal(var))
            except ValueError:
                # Otherwise we'll set self.lookups so that resolve() knows we're
                # dealing with a bonafide variable
                if VARIABLE_ATTRIBUTE_SEPARATOR + "_" in var or var[0] == "_":
                    raise TemplateSyntaxError(
                        "Variables and attributes may "
                        "not begin with underscores: '%s'" % var
                    )
                self.lookups = tuple(var.split(VARIABLE_ATTRIBUTE_SEPARATOR))
def __repr__(self)
django.template.base.Variable
Return repr(self).
    def __repr__(self):
        return "<%s: %r>" % (self.__class__.__name__, self.var)
def __str__(self)
django.template.base.Variable
Return str(self).
    def __str__(self):
        return self.var
def resolve(self, context)
django.template.base.Variable
Resolve this variable against a given context.
    def resolve(self, context):
        """Resolve this variable against a given context."""
        if self.lookups is not None:
            # We're dealing with a variable that needs to be resolved
            value = self._resolve_lookup(context)
        else:
            # We're dealing with a literal, so it's already been "resolved"
            value = self.literal
        if self.translate:
            is_safe = isinstance(value, SafeData)
            msgid = value.replace("%", "%%")
            msgid = mark_safe(msgid) if is_safe else msgid
            if self.message_context:
                return pgettext_lazy(self.message_context, msgid)
            else:
                return gettext_lazy(msgid)
        return value