duanlie1298 2017-05-27 16:45
浏览 30
已采纳

简单的用树枝分页

I'm trying to create a simple pagination with a twig view. I'm not using Symfony.

Here is my method from my manager :

  public function getAllPosts()
  {
      if(isset($_GET['p']) && (!isset($_GET['page']))){

          $currentPage =  1;
      }
      else {
          $currentPage = $_GET['page'];
      }
    $q= $this->_db->query('SELECT COUNT(id) AS numberposts FROM posts');
    $data = $q->fetch(PDO::FETCH_ASSOC);

    $number_posts= $data['numberposts'];
    $perPage = 1;
    $numberPages = ceil($number_posts/$perPage);

    $q = $this->_db->query("SELECT * FROM posts ORDER BY date DESC LIMIT ".(($currentPage-1)*$perPage).",$perPage");

    while($data = $q->fetch(PDO::FETCH_ASSOC))
    {
      $datas[] = new Post($data);
    }


    return $datas;

  }

I want to create a loop in my view, this is what I'm doing

            {% for posts in allPosts %}
               {% for i in 1..numberPages %}
                    <a href="index.php?p=blog&page={{ i }}">{{ i }}</a>
                 {% endfor %}
            {% endfor %}

But it's not working. It seems like I can't access to numberPages and I don't know why.

If anybody can help me !

Thanks a lot

EDIT

My pagination is working now.

I had this in my method like @darkbee :

        return array(
    'records'     => $datas,
    'numberPages' => $numberPages,
);

And in my view :

{% for i in 1.. allPosts.numberPages %}
                    <li><a href="index.php?p=blog&page{{ loop.index }}">{{ loop.index}}</a></li>
                {% endfor %}

But now I have another issue. I only get the same posts in all the pages.

EDIT

I forgot the page= on my pages links ...

 <li><a href="index.php?p=blog&page={{ loop.index }}">{{ loop.index}}</a></li>

It's working now !

Thanks !

  • 写回答

1条回答 默认 最新

  • dth62818 2017-05-27 17:58
    关注

    You need to return the number of pages as well. An aproach could be this,

    public function getAllPosts()  {
        /** ... code .. **/
        return array(
            'records'     => $data,
            'numberPages' => $numberPages,
        );
    }
    
    
    
    {% for posts in allPosts.records %}
        {% for i in 1.. allPosts.numberPages %}
             <a href="index.php?p=blog&page={{ i }}">{{ i }}</a>
        {% endfor %}
    {% endfor %}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分