从Django的循环中提取值 [英] Extracting a value from inside a django loop

查看:316
本文介绍了从Django的循环中提取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Django应用程序,其中我使用模板中的以下内容:

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?

我想是这样的:

<span ng-bind="progid = {{node.program_id}}"></span> 

但是,当我提到这外循环,这是行不通的!

But when i refer it outside the loop, it does not work!

更新:

你可以看到,我想使用进程id的值外循环。

as you can see, i am trying to use the value of progid outside the loop.

推荐答案

您可以尝试为此编写自定义模板标签。请参阅该文档。

You may try to write a custom template tag for this. See the docs.

https://docs.djangoproject.com/en/dev / HOWTO /自定义模板标签/

假设你的任务标签被命名为分配,你会再做

Assuming your assignment tag is named assign, you would then do

{% recursetree nodes %}

    {% assign_node node %}

{% endrecursetree %}

然后使用 my_node

{{ my_node.program_id }}

您的模板标签code应该得到的上下文。主上下文总是context.dicts [0]

Your template tag code should be getting the context. The main context is always the context.dicts[0].

您的模板标签模块(名为 bar_tags

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.

这篇关于从Django的循环中提取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆