开发者

Using a variable as an object key in Django Template Tags

I have two 4 tier objects that I am passing to the django template. I am currently for looping through each tier, and going down a level if it exists. I ended up having key, key2 and key3 that represents the current location in the object while looping. I would like to reference the other object that has the same tiers using those variables, but am having some trouble.

If I was trying to do this in python, it would look like this

my_object[ key ][ key2 ][ key3 ]

But in django templates, it doesn't seem I can use brackets, and if I used periods it would think key is the key name, and not look at it as a variable.

If you need more details on my code, let me know. Thanks!

Edit: Here is an example of what my object looks like, and my template code.

variable1 = {
    "content": {
        "pages": {
            "view":True,
            "add":True,
            "edit":True,
            "delete":True
        },
        "articles": {
            "view":True,
            "add":True,
            "edit":True,
            "delete":True
        },
        "slideshow": {
            "view":True,
            "edit":True
        },
    },
    "people": {
        "view":True,
        "add":True,
        "edit":True,
        "delete":True,
        "sort-staff":True,
        "sort-riders":True
    }
}

variable2 is the same as variable one, with the same keys, but some keys are missing.

Here is what my template looks like to sort through this object.

{% for key, value in variable1.items %}
    <strong>{{ key|title }}</strong>
    {% for key2, value2 in value.items %}
        {% if value2.items %}
            <p class="indent">{{ key2|title }}
            {% for key3, value3 in value2.items %}
                <p class="indent"><input type="checkbox" name="form_permission_{{ key }}_{{ key2 }}_{{ key3 }}" {% if variable2[key][key2][key3] %}checked="checked"{% endif %}> {{ key3|title }}</p>
            {% endfor %}
            </p>
        {% else %}
            <p class="indent"><input type="checkbox" name="form_permission_{{ key }}_{{ key2 }}"> {{ key2|title }}</p>
        {% endif %}
    {% endfor %}
{% endfor %}

If you look at the most inden开发者_运维百科ted line, you will see {% if variable2[key][key2][key3] %}checked="checked"{% endif %}. You should be able to understand what I'm trying to accomplish with that code.


That cannot be done this way. Look into writing a template tag or filter for this.


I ended up doing the sorting and comparing before the data was sent to the template so this question is no longer needed. Feel free to post other options.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜