【问题标题】:append (query string) parameters to the current url将(查询字符串)参数附加到当前 url
【发布时间】:2013-07-20 12:32:43
【问题描述】:

快递,

假设我在http://localhost:3000/search?q=foo&sort=asc

在我的模板中,如何打印带有附加参数的链接(比如下一个分页链接):

search.dust

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

--

当然,我可以:

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

但由于?/&amp; 问题,当我在http://localhost:3000/search 时它不起作用。

谢谢

【问题讨论】:

标签: express dust.js


【解决方案1】:

为此我made a dust helper。我称它为{@query},这是它的签名:

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

它将que=ry&amp;str=ing 与实际的req.query 参数合并,因此在前面的示例中我们使用http://localhost:3000/search?q=foo&amp;sort=asc

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

将输出:

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

--

实现如下(在可以访问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();
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多