class ForNode
from django.template.defaulttags import ForNode
Ancestors (MRO)
Attribute | Type | Defined in |
---|---|---|
__dict__ |
getset_descriptor
|
django.template.base.Node |
__weakref__ |
getset_descriptor
|
django.template.base.Node |
Attribute | Value | Defined in |
---|---|---|
child_nodelists |
('nodelist_loop', 'nodelist_empty') |
django.template.defaulttags.ForNode |
child_nodelists |
('nodelist',) |
django.template.base.Node |
must_be_first |
False |
django.template.base.Node |
token |
None |
django.template.base.Node |
def __init__(self, loopvars, sequence, is_reversed, nodelist_loop, nodelist_empty=None)
django.template.defaulttags.ForNode
Initialize self. See help(type(self)) for accurate signature.
def __init__(
self, loopvars, sequence, is_reversed, nodelist_loop, nodelist_empty=None
):
self.loopvars = loopvars
self.sequence = sequence
self.is_reversed = is_reversed
self.nodelist_loop = nodelist_loop
if nodelist_empty is None:
self.nodelist_empty = NodeList()
else:
self.nodelist_empty = nodelist_empty
def __repr__(self)
django.template.defaulttags.ForNode
Return repr(self).
def __repr__(self):
reversed_text = " reversed" if self.is_reversed else ""
return "<%s: for %s in %s, tail_len: %d%s>" % (
self.__class__.__name__,
", ".join(self.loopvars),
self.sequence,
len(self.nodelist_loop),
reversed_text,
)
def get_nodes_by_type(self, nodetype)
django.template.base.Node
Return a list of all nodes (within this node and its nodelist) of the given type
def get_nodes_by_type(self, nodetype):
"""
Return a list of all nodes (within this node and its nodelist)
of the given type
"""
nodes = []
if isinstance(self, nodetype):
nodes.append(self)
for attr in self.child_nodelists:
nodelist = getattr(self, attr, None)
if nodelist:
nodes.extend(nodelist.get_nodes_by_type(nodetype))
return nodes
def render(self, context)
django.template.defaulttags.ForNode
django.template.defaulttags.ForNode
Return the node rendered as a string.
def render(self, context):
if "forloop" in context:
parentloop = context["forloop"]
else:
parentloop = {}
with context.push():
values = self.sequence.resolve(context, ignore_failures=True)
if values is None:
values = []
if not hasattr(values, "__len__"):
values = list(values)
len_values = len(values)
if len_values < 1:
return self.nodelist_empty.render(context)
nodelist = []
if self.is_reversed:
values = reversed(values)
num_loopvars = len(self.loopvars)
unpack = num_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
pop_context = False
if unpack:
# If there are multiple loop variables, unpack the item into
# them.
try:
len_item = len(item)
except TypeError: # not an iterable
len_item = 1
# Check loop variable count before unpacking
if num_loopvars != len_item:
raise ValueError(
"Need {} values to unpack in for loop; got {}. ".format(
num_loopvars, len_item
),
)
unpacked_vars = dict(zip(self.loopvars, item))
pop_context = True
context.update(unpacked_vars)
else:
context[self.loopvars[0]] = item
for node in self.nodelist_loop:
nodelist.append(node.render_annotated(context))
if pop_context:
# Pop the loop variables pushed on to the context to avoid
# the context ending up in an inconsistent state when other
# tags (e.g., include and with) push data to context.
context.pop()
return mark_safe("".join(nodelist))
django.template.base.Node
Return the node rendered as a string.
def render(self, context):
"""
Return the node rendered as a string.
"""
pass
def render_annotated(self, context)
django.template.base.Node
Render the node. If debug is True and an exception occurs during rendering, the exception is annotated with contextual line information where it occurred in the template. For internal usage this method is preferred over using the render method directly.
def render_annotated(self, context):
"""
Render the node. If debug is True and an exception occurs during
rendering, the exception is annotated with contextual line information
where it occurred in the template. For internal usage this method is
preferred over using the render method directly.
"""
try:
return self.render(context)
except Exception as e:
if context.template.engine.debug:
# Store the actual node that caused the exception.
if not hasattr(e, "_culprit_node"):
e._culprit_node = self
if (
not hasattr(e, "template_debug")
and context.render_context.template.origin == e._culprit_node.origin
):
e.template_debug = (
context.render_context.template.get_exception_info(
e,
e._culprit_node.token,
)
)
raise