2013-07-21 48 views
0

在快递,追加(查询字符串)参数当前URL

假设我在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> 

,但是当我因为?/&问题在http://localhost:3000/search,这是行不通的。

谢谢

+0

这应该在客户端的工作:如何参数添加到已包含其他参数,也许一个锚URL]( http://stackoverflow.com/questions/6953944/how-to-add-parameters-to-a-url-that-already-contains-other-parameters-and-maybe)。也许你可以适应它在快速路线或模板中工作? –

回答

2

我为此made a dust helper。我把它叫做{@query}这里是它的签名:

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

它融合que=ry&str=ing实际req.query参数,因此在前面的例子中,我们是在http://localhost:3000/search?q=foo&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(); 
}); 
相关问题