How do I return a list as a variable in Python and use in Jinja2?
Question: I am a very young programmer and I am trying to do something in Python but I'm
stuck. I have a list of users in Couchdb (using python couchdb library & Flask
framework) who have a username (which is the _id) and email. I want to use the
list of email addresses in a select box in a jinja2 template.

My first problem is how to access the email addresses. If I do:

    
    
    for user in db:
        doc = db[user]
        emails = doc['email']
        print options
    

I get:

    
    
    email@domain.com
    otheremail@otherdomain.com
    yetanotheremail@yetanotherdomain.com
    

So I can get my list of emails. But where my brutal inexperience is showing up
is that I don't know how to then use them. The list only exists in the for
loop. How do I return that list as a useable list of variables? And how do I
then make that list appear in my jinja2 template in an option dropdown. I
guess I need a function but I am a green programmer.

Would so appreciate help.


Answer: 
    # assuming you have something such as this:
    class User(Document):
        email = TextField()
    
    # you can use the .load() method of the User class
    users = [User.load(db, uid) for uid in db]
    
    # now you can do this:
    for user in users:
        print user.id, user.email  
    
    # but you're using it in flask so, in your view you can send 
    # this list of users to your template using something like this:
    
    from flask import render_template
    @app.route("/users")
    def show_users():
        return render_template('users.html', users=users)
    

Now in your users.html jinja2 template the following will output a dropdown
listbox of each user's e-mail

    
    
    <select>
    {% for user in users %}
        <option value="{{ user.id }}">{{ user.email }}</option>
    {% endfor %}
    </select>
    

Also, are you using the Flask-CouchDB extension? It might be helpful in
abstracting out some of the low level couchdb coding:
<http://packages.python.org/Flask-CouchDB/>

Disclaimer: The code above wasn't tested, but should work fine. I don't know
much about CouchDB, but I am familiar with Flask. Also, I obviously didn't
include a full Flask/CouchDB application here, so bits of code are missing.

