Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django array or list output?

I'm pulling a set of image urls and their respective titles. I've tried creating a hash or associative array, but the data seems to overwrite so I only end up with the last item in the array.

For example;

thumbnail_list = []
for file in media:
    thumbnail_list['url'] = file.url
    thumbnail_list['title'] = file.title

I've even tried creating two lists and putting them in a larger one.

thumbnail_list.append('foo')
thumbnail_urls.append('bar')
all_thumbs = [thumbnail_list], [thumbnail_urls]

I'm trying to create a link out of this data:

<a href="image-url">image title</a>

I keep getting close, but I end up looping over too much data or all of the data at once in my django template.

Ideas?

Edit: Maybe zip() is what I need?

questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
    print 'What is your {0}?  It is {1}.'.format(q, a)
like image 524
Shu Avatar asked Feb 24 '10 00:02

Shu


1 Answers

You want a dict, which is Python's associative data structure, whereas you are creating a list.

But I'm not sure I understand your problem. Why not just pass your media collection into the template and iterate like this:

{% for file in media %}
    <a href="{{ file.url }}">{{ file.title }}</a>
{% endfor %}

EDIT

Based on your comment, I now presume you are looking for something like this:

thumbnail_list = []
for file in media:
    file_info = {}
    file_info['url'] = file.url
    file_info['title'] = file.title
    thumbnail_list.append(file_info)

{% for file in thumbnail_list %}
    <a href="{{ file.url }}">{{ file.title }}</a>
{% endfor %}

You can create a list, then for each file, append a dictionary into that list after you've processed the URL, title, or whatever.

Or, you could create your own class that encapsulates this a little better in case you have other logic to apply:

class FileInfo(object):
    def __init__(self, file):
        self.url = file.url # do whatever
        self.title = file.title # do whatever

thumbnail_list = []
for file in media:
    thumbnail_list.append(FileInfo(file))
like image 146
Joe Holloway Avatar answered Oct 06 '22 01:10

Joe Holloway