views:

37

answers:

2

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 indented 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.

A: 

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

Ignacio Vazquez-Abrams
I was pretty sure this couldn't be done, but it seems like something a lot of people might find themselves needing. My hope was to find something someone already wrote (custom tag or filter) that I can plug in.
Shane Reustle
A: 

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.

Shane Reustle