Variable variables

3 views
Skip to first unread message

rvidal

unread,
Sep 16, 2009, 12:18:05 PM9/16/09
to Django users
Hi,

I have the following situation:

I have a dictionary with dictionaries nested, like so:

cutsites = {'rfc10': {'EcoRI':[20, 112], 'XbaI':[5, 12, 45], 'SpeI':
[45, 129, 245]},
'rfc21': {'EcoRI':[2, 22], 'XbaI':[15, 42, 66],
'SpeI':[55, 69, 95]}
}

And I also have the following dictionary:

rs_sites = {'EcoRI': 'GAATTC',
'XbaI': 'TCTAGA',
'SpeI': 'ACTAGT'
}

Now in my template I run through the cutsites dictionary and present
the content as so:
{% for renz,csites in cutsites.rfc21.items %}
{{ renz }} (Site: {{ rs_sites.{{ renz }} }}):
{% if not csites %}
NA
{% else %}
{% for sites in csites %}
<span class="bad">{{ sites }}, </span>
{% endfor %}
{% endif %}
;&nbsp;
{% endfor %}

I need to call the rs_sites value based on the renz variable and was
hoping I could stick a variable within a variable like so:
{{ rs_sites.{{ renz }} }}

I've tried using {% ifequal %} with the keys and values within the for
but without success as shows below (I know, what a mess!):

{% for renz,csites in cutsites.rfc21.items %}
{{ renz }}
{% for enz, string in rs_sites.items %}
{% ifequal enz renz %}
{{ string }}
{% endifequal %}
{% endfor %}
{% if not csites %}
NA
{% else %}
{% for sites in csites %}
<span class="bad">{{ sites }}, </span>
{% endfor %}
{% endif %}
;&nbsp;
{% endfor %}


I can see that I'm using too much logic in my template but was hoping
it would be possible without having to go into making custom tags.

Thanks in advance for any help provided.

Kind regards,
Ricardo

James Punteney

unread,
Sep 16, 2009, 1:22:22 PM9/16/09
to django...@googlegroups.com
Hi Ricardo,


On Wed, Sep 16, 2009 at 12:18 PM, rvidal <rvi...@gmail.com> wrote:
I can see that I'm using too much logic in my template but was hoping
it would be possible without having to go into making custom tags.


If there is too much logic in the template in general there are two options.
1. Create a templatetag with the logic
2. Do the logic within the view so you can do a simple loop in the template

If you are wanting to use the output in many different templates/views then your best bet is to use a templatetag as that is easier to include multiple places. If you only need the logic for one template/view then I'd recommend processing the data in the view function to turn it into simple list or similar object that you can easily loop through in the template without all the additional logic.

--James

rvidal

unread,
Sep 16, 2009, 1:54:44 PM9/16/09
to Django users
Thank you James,

I'm in the process of breaking this down in the view. Should have
thought about that earlier.

Thanks again!

R
Reply all
Reply to author
Forward
0 new messages