如何控制一个html中显示的项目数?

时间:2018-06-19 04:09:50

标签: python html flask

如何控制一个html中显示的项目数?

我想在一个html中显示5个项目。当我有21个项目时,我希望有5个页面的分页。我正在制作Flask应用程序,所以我在app.py中写道

@app.route("/page", methods=["GET","POST"])
def page():

    users = {
        "data":[
            {
                “Name”:”Tom”,
                “Age”:”21”
            },
            {
                “Name”:”John”,
                “Age”:”40”
            },
            {
                “Name”:”Juddy”,
                “Age”:”37”
            },
            {
                “Name”:”Kei”,
                “Age”:”46”
            },
            {
                “Name”:”Wu”,
                “Age”:”12”
            },
            {
                “Name”:”Rey”,
                “Age”:”47”
            },
            {
                “Name”:”Boo”,
                “Age”:”25”
            },
            {
                “Name”:”Cho”,
                “Age”:”48”
            }
        ],
        “Date”:”20180403”
    }

   users = users["data"]


    page = request.args.get(get_page_parameter(), type=int, default=5)
    pagination = Pagination(page=page, total=len(users), search=search)


    return render_template(“index.html", json=users,pagination=pagination)

并在index.html中写道

<div>
    {% for i in range(json|length) %}
    <div>
            <h3>{{ json[i]['Name'] }}</h3>
        <h3>{{ json[i]['Age'] }}</h3>
    </div>
    {% endfor %}
</div>

{{ pagination.info }}
{{ pagination.links }}

但现在所有8个数据都显示在一个index.html中。我想在一个页面中显示5个项目,在下一页显示3个项目,但我的代码有什么问题?我应该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

page = 1 # read the page no dynamically

类似于您在下面的行

page = request.args.get(get_page_parameter(),type = int,default = 5)

pagesize = 5 # always use variable for constants

start = (page - 1) * pagesize # calculation of startpoint of list slicing
end = page * pagesize # calculation of endpoint of list slicing
users = users[start:end]

答案 1 :(得分:0)

您可以使用一个类构建一个简单的分页对象,该类可以将传递给该路由的任何页码的属性数据分组。

首先,创建分页类。此类接收当前页码,并返回要在该页面上列出的用户。该类还可以从json文件中读取源数据,尽管该步骤可以交换为数据库连接或其他自定义数据选择。另外,HTML模板将需要包含带有previousnext,页面和当前页面a href的页脚,以链接所有分页。为此,将特殊属性添加到该类:

import json #only needed if reading data from json file
import collections
def adjust_pagination(f):
  def _wrapper(cls):
    if cls._page_number < 0:
      setattr(cls, '_page_number', 1)
    elif cls._page_number > len(cls._data):
      setattr(cls, '_page_number', len(cls._data))
    return f(cls)

class Pagination:
   def __init__(self, per_page = 5, default = 1, source = json.load(open('filename.txt'))['data']):
     self._data = [source[i:i+per_page] for i in range(0, len(source), per_page)]
     self._page_number = default
   @property
   def next(self):
     return self._page_number + 1 if self._page_number < len(self._data) else len(self._data)
   @property
   def previous(self):
     return self._page_number - 1 if self._page_number > 1 else 1
   @property
   def footer(self):
      atag = collections.namedtuple('atag', ['value', 'iscurrent'])
      return [atag(i+1, i+1 == self._page_number) for i in range(1, len(self._data)+1)]
   @adjust_pagination
   def __iter__(self):
     user = collections.namedtuple('user', ['name', 'age'])
     for _user in self._data[self._page_number-1]:
       yield user(*[_user[i] for i in ['Name', 'Age']])
   def __repr__(self):
       return '/view_users/'

然后,使用参数创建应用以接收所需的页面:

@app.route('/view_users/<page>', methods=['GET'])
def user_pannel(page):
  return flask.render_template('users.html', to_display = Pagination(default=int(page)))

最后,创建users.html。对于自定义分页a href标签,此答案使用引导程序:

<html>
 <head>
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
 </head>
   <body>
   </body>
    <h1>Current users:</h1>
    {%for user in to_display%}
       <span>Name: {{user.name}}, Age: {{user.age}}</span>
    {%endfor%}
   <div class='spacer' style='height:20px'></div>

  <nav aria-label="pagination">
    <ul class="pagination">
      <li class="page-item"><a class="page-link" href="{{to_display}}{{to_display.previous}}">Previous</a></li>
      {%for block in to_display.footer%}
        {%if block.iscurrent%}
          <li class="page-item active">
           <a class="page-link" href="{{to_display}}{{block.value}}">{{block.value}} <span class="sr-only">(current)</span></a>
         </li>
        {%else%}
          <li class="page-item"><a class="page-link" href="{{to_display}}{{block.value}}">{{block.value}}</a></li>
        {%endif%}
     {%endfor%}
     <li class="page-item">
      <a class="page-link" href="{{to_display}}{{to_display.next}}">Next</a>
     </li>

  </ul>
 </nav>
</html>