0

In express,

Suppose I'm at http://localhost:3000/search?q=foo&sort=asc

In my template, how can I print a link (say a next pagination link) with additional parameters:

search.dust

<a rel="next" href="{! append page=2 !}">Next results</a>

--

Of course, I could:

<a rel="next" href="{currentUrl}&page=2">Next results</a>

but it would not work when I'm at http://localhost:3000/search, because of the ?/& issue.

Thank you

abernier
  • 27,030
  • 20
  • 83
  • 114
  • This should work on the client side: [How to add parameters to a URL that already contains other parameters and maybe an anchor](http://stackoverflow.com/questions/6953944/how-to-add-parameters-to-a-url-that-already-contains-other-parameters-and-maybe). Maybe you could adapt it to work in an Express route or in the template? – Dan Ross Jul 21 '13 at 22:08

1 Answers1

2

I made a dust helper for this. I called it {@query} and here is its signature:

{@query string="que=ry&str=ing"/}

It merges que=ry&str=ing with actual req.query parameters, thus in the previous example where we were on http://localhost:3000/search?q=foo&sort=asc:

<a rel="next" href="?{@query string="page=2"/}">Next</a>

will output:

<a rel="next" href="?q=foo&sort=asc&page=2">Next</a>

--

The implementation is as followed (inside a middleware to have access to req.query):

var dust = require('dustjs-linkedin');
var _ = require('underscore');
var qs = require('querystring');
app.use(function(req, res, next) {
  //
  // Query helper for dust
  //
  // Merge querystring parameters to the current req.query
  //
  // Suppose we are on localhost:3000/search?q=foo :
  //   - {@query string=""/} will output q=foo
  //   - {@query string="bar=baz"/} will output q=foo&bar=baz
  //   - {@query string="q=fooo&bar=baz"/} will output q=fooo&bar=baz (notice fooo takes precedence)
  //
  dust.helpers.query = function (chunk, ctx, bodies, params) {
    var str = dust.helpers.tap(params.string, chunk, ctx);

    // Parse string="" parameter
    var o = qs.parse(str);

    // Merge with req.query
    o = _.extend({}, req.query, o);

    return chunk.write(qs.stringify(o));
  }

  next();
});
abernier
  • 27,030
  • 20
  • 83
  • 114