从列表中生成随机ID-Jinja [英] Generating random ID from list - jinja

查看:106
本文介绍了从列表中生成随机ID-Jinja的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从联系人列表(在python中,使用jinja2)生成一个随机ID,以显示在HTML模板中.

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

所以我有一个联系人列表,目前,我通过遍历联系人列表在HTML模板的几个单元格中显示了所有联系人:

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),
   )

相反,我想显示一个由其ID随机选择的联系人,并且每当用户刷新页面时,它都应显示另一个联系人及其所有信息(到目前为止,我不打算两次显示相同的联系人方式).

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).

我知道可以在python文件中使用random处理随机选择,因此但不确定在模板中的jinja中如何翻译.

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.

任何帮助表示感谢!

推荐答案

jinja2中有一个random过滤器.

随机(seq)

从序列中返回随机项目.

Return a random item from the sequence.

像这样使用它:

{% set selected_contact = contact_dbs|random %}

注意:我假设contact_dbsiterable.

这篇关于从列表中生成随机ID-Jinja的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆