问题
I have a django app where i am using the following in the templates:
{% load mptt_tags %}
<ul>
{% recursetree nodes %}
<li>
{{ node.name }}
{% if not node.is_leaf_node %}
<ul class="children">
{{ children }}
</ul>
{% endif %}
{% if node.is_leaf_node %}
<span ng-bind="progid = {{node.program_id}}"></span>
{% endif %}
</li>
{% endrecursetree %}
</ul>
The values of the node will be gone once the recursion takes place. I would like to know how to extract a values outside this loop in the template such that it can be used in another template?
I tried something like this:
<span ng-bind="progid = {{node.program_id}}"></span>
But when i refer it outside the loop, it does not work!
UPDATE:
as you can see, i am trying to use the value of progid outside the loop.
回答1:
You may try to write a custom template tag for this. See the docs.
https://docs.djangoproject.com/en/dev/howto/custom-template-tags/
Assuming your assignment tag is named assign, you would then do
{% recursetree nodes %}
{% assign_node node %}
{% endrecursetree %}
And then use the my_node
{{ my_node.program_id }}
Your template tag code should be getting the context. The main context is always the context.dicts[0].
Your template tags module (named bar_tags):
from django import template
register = template.Library()
@register.assignment_tag(takes_context=True)
def get_dummy_nodes(context, *args, **kwargs):
"""
Just get some dummy objects to work with.
"""
class Node(object):
name = None
def __init__(self, program_id):
self.program_id = program_id
nodes = []
for i in range(0, 10):
nodes.append(Node(i))
return nodes
@register.simple_tag(takes_context=True)
def assign_node(context, node, *args, **kwargs):
"""
Puts your variable into the main context under name ``my_node``.
"""
context.dicts[0]['my_node'] = node
return ''
Your template:
<html>
<body>
{% load bar_tags %}
{% get_dummy_nodes as nodes %}
{% for node in nodes %}
{% assign_node node %}
{% endfor %}
my_node {{ my_node.program_id }}
</body>
</html>
Note: you should better be doing such things in a view.
来源:https://stackoverflow.com/questions/24247130/extracting-a-value-from-inside-a-django-loop