Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating random ID from list - jinja

I am trying to generate a random ID from a list of contacts (in Python, with jinja2) to display in an HTML template.

So I have a list of contacts, and for the moment I display all of them in a few cells in my HTML template by looping through the list of contacts:

# for contact_db in contact_dbs
    <tr>
      <td>{{contact_db.key.id()}}</td>
      <td>{{contact_db.name}}</td>
      <td>{{contact_db.phone}}</td>
      <td>{{contact_db.email}}</td>
    </tr>
  # endfor

The view that renders the above is:

def contact_list():
  contact_dbs, contact_cursor = model.Contact.get_dbs(
  user_key=auth.current_user_key(),
  )
  return flask.render_template(
   'contact_list.html',
    html_class='contact-list',
    title='Contacts',
    contact_dbs=contact_dbs,
    next_url=util.generate_next_url(contact_cursor),
   )

Instead, I would like to display one contact, selected randomly by its ID, and it should display another contact with all its information every time the user refreshes the page (I am not dealing with displaying the same contact twice for now by the way).

I know that it is possible to use random in a python file to deal with random choices, so but not sure how it translates in jinja in the template.

Any help appreciated thanks!

like image 747
David B. Avatar asked Apr 06 '15 13:04

David B.


1 Answers

There is a random filter in jinja2.

random(seq)

Return a random item from the sequence.

Use it like this:

{% set selected_contact = contact_dbs|random %}

note: I assumed contact_dbs is iterable.

like image 98
Assem Avatar answered Oct 13 '22 14:10

Assem