Express-Handlebars:获取当前 URL 查询并将查询传递给模板?

aug*_*aug 3 node.js express handlebars.js

目前我已经设置了Express3-Handlebars,我正在尝试获取当前 URL,提取 GET 查询,并将其传递到辅助函数中的车把模板。不过,我无法找到一种方法来将发送到车把助手的请求传递给我,因为我似乎只能访问路线中的当前 URL。

app.get('/somewhere', function(req, res) {
  console.log(req.originalUrl); <-- prints the URL I am at such as somewhere?country=US
  res.render('somewhere-home', {
    somewhere-info: global.somewhere-info
    globals: global.globals,
    css:['/media/css/somewhere.css'
    ],
    js:[
        '/media/js/somewhere.js'
    ]
  });
});
Run Code Online (Sandbox Code Playgroud)

我希望编写一个辅助函数,可以利用节点的url库并将 URL 传递给 Handlebars

helpers: {
        currentURL: function() { 
            console.log(url.parse(req.originalUrl, true));
            return url.parse(req.originalUrl, true);
        },
Run Code Online (Sandbox Code Playgroud)

然后我可以在我的车把文件中以某种方式访问​​它。我希望我的模板能够智能地打印一些东西,但是如果我收到某个请求,则打印另一件事。所以像

{{#if currentURL.query == 'US' }}
    <h1>Welcome to US!</h1>
{{else}}
    <h1>Welcome to wherever the hell you are from!</h1>
{{/if}}
Run Code Online (Sandbox Code Playgroud)

不确定我是否以错误的方式处理这个问题。我在Express 的app.get文档中读到,您可以处理某些 GET 请求并根据它们渲染特定页面,但我真的只想更改车把模板文件中的一件小事情,所以我希望不必为每个请求创建多个车把模板我要处理的 GET 请求。或者也许这是解决问题的正确方法?

aug*_*aug 6

所以我想通了。很傻。我在模板中定义了一个范围,因此它只能访问info变量。

{{#info}}
 <h1>{{header}}</h1>
 ...

{{/info}}
Run Code Online (Sandbox Code Playgroud)

req变量发送一个query字段供我使用,因此我最终根本不需要辅助函数。您可以在此处一直底部查找更多内容。

app.get('/info', function(req, res) {
  //set context of handlebars
  res.render('info', {
     info  : {
        header : "View Title"
     },
     query : req.query
  }
}
Run Code Online (Sandbox Code Playgroud)

由于 Handlebars 的工作原理,您可以简单地将上下文添加到渲染函数中。然后它将可用。

让我困惑的是瞄准镜,所以在我的把手模板中,我只是简单地打开和关闭瞄准镜。

{{#info}}
  <h1>{{header}}</h1>
  ...
{{/info}}
  {{#if query.country}}
    <h2>Welcome to the {{query.country}}!</h2>
  {{else}}
    <h2>Welcome!</h2>
  {{/if}}
{{#info}}
  ... continue
{{/info}}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。