loading...

Discussion on: Create a blog with Sapper & Markdown

Collapse
rdricco profile image
renato ricco

Any suggestion for pagination? Its one of most basic features of a Blog.

Collapse
joshnuss profile image
Joshua Nussbaum Author

That is true, pagination is important.

Here's one way to do it:

1) Group posts into pages/chunks inside src/posts.js

// 10 posts per page
export const pages = _.chunk(posts, 10)
Enter fullscreen mode Exit fullscreen mode

2) Inside routes/index.svelte, define a preload function that looks at the query params:

<script context="module">
  import {pages} from '../posts'

  export function preload(page) {
    const index = +(page.query.page || 1)

    return {
      posts: pages[index-1],
      hasMore: pages.length > index + 1,
      page: index
    }
  }
</script>

<script>
  export let posts, hasMore, page
</script>
Enter fullscreen mode Exit fullscreen mode

3) Add conditional next & previous links

{#if page > 1}
  <a href="/?page={page-1}">Previous</a>
{/if}

{#if hasMore}
  <a href="/?page={page+1}">Next</a>
{/if}
Enter fullscreen mode Exit fullscreen mode

Hope that helps!

Collapse
rdricco profile image
renato ricco

Nice! Thank you,