How do I return a list as a variable in Python and use in Jinja2?

前端 未结 3 1661
盖世英雄少女心
盖世英雄少女心 2021-02-05 18:45

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

相关标签:
3条回答
  • 2021-02-05 19:12

    You pass parameters to a jinja template as a dictionary d when you call the template.renderfunction(d) function (for example). Thus, you could do:

    emails = []
    for user in db:
        doc = db[user]
        emails.append(doc['email'])
    some_jinja_template.render({'list_of_emails' : emails})
    

    Then in the template, you could do something like:

    <ul>
    {% for address in list_of_emails %}
        <li><a href="mailto:{{ address }}">Send email to {{ address }}</a></li>
    {% endfor %}
    </ul>
    

    To make a list of emails, for example, or handle them however you'd like.

    PS - I'm sure the code could be more elegant/more optimized with a list comprehension or whatever, but I figured I should emphasize readability for a so-called "green" programmer.

    0 讨论(0)
  • 2021-02-05 19:21
    lista = [ x for x in db ] # watch out for big databases, you can run out of memory
    
    0 讨论(0)
  • 2021-02-05 19:36

    Assuming you have a model such as:

    class User(Document):
        email = TextField()
    

    You can use the static method load 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():
        users = [User.load(db, uid) for uid in db]
        return render_template('users.html', users=users)
    

    Now in the 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.

    0 讨论(0)
提交回复
热议问题