2
\$\begingroup\$

I've build a handlebars helper that takes n total pages and currentPage and returns the HTML for the page number links, skipping out pages far away from the current page to avoid it being too big. I feel like there are a lot of if statements in there and it could be a bit more compact.

enter image description here

'use strict';

var config = require('config');
var pagesInGroup = config.pagesInGroup;

module.exports =  function(n, currentPage, block) {
    var accum = '';
    var preEllipsis = '';
    var postEllipsis = '';
    currentPage = parseInt(currentPage, 10);
    n = parseInt(n, 10);

    if (currentPage > (pagesInGroup / 2) + 1) {
        preEllipsis = '<li><a>...</a></li>';
    }
    if (currentPage < n - (pagesInGroup / 2)) {
        postEllipsis = '<li><a>...</a></li>';
    }

    if (currentPage === 1) {
        accum += '<li class="active"><a href="?page=1">1</a></li>'+preEllipsis;
    } else {
        accum += '<li><a href="?page=1">1</a></li>'+preEllipsis;
    }

    for(var page = 2; page < n; page++) {
        if (page !== currentPage && page <= currentPage + (pagesInGroup / 2) && page >= currentPage - (pagesInGroup / 2)) {
          accum += '<li><a href="?page='+page+'">'+page+'</a></li>';
        } else if (page === currentPage) {
          accum += '<li class="active"><a href="?page='+page+'">'+page+'</a></li>';
        }
    }

    if (n === currentPage && n>1) {
        accum += postEllipsis+'<li class="active"><a href="?page='+n+'">'+n+'</a></li>';
    } else if (n>1) {
        accum += postEllipsis+'<li><a href="?page='+n+'">'+n+'</a></li>';
    }

    return accum;
};
\$\endgroup\$

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.