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

时间:2014-10-26 06:18:54

标签: node.js express handlebars.js

目前我已设置Express3-Handlebars,我正在尝试获取当前网址,解压缩GET查询,并将其传递给辅助功能中的手柄模板。我很难找到一种方法来传递发送给我的车把帮手的请求,因为我似乎只能访问路线中的当前网址。

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'
    ]
  });
});

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

helpers: {
        currentURL: function() { 
            console.log(url.parse(req.originalUrl, true));
            return url.parse(req.originalUrl, true);
        },

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

这样的东西
{{#if currentURL.query == 'US' }}
    <h1>Welcome to US!</h1>
{{else}}
    <h1>Welcome to wherever the hell you are from!</h1>
{{/if}}

不确定我是否以错误的方式解决这个问题。我在Express's app.get documentation读到你可以处理某些GET请求并根据它们呈现特定页面,但我真的只想改变我的把手模板文件中的一个小东西,所以我希望我不必创建我想要处理的每个GET请求的多个把手模板。或许这是正确的解决方法?

1 个答案:

答案 0 :(得分:4)

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

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

{{/info}}

req变量发送query字段供我使用,所以我最终根本不需要辅助函数。您可以查找更多here all the way at the bottom

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

由于Handlebars的工作原理,您只需向渲染功能添加上下文即可。它随后可用。

让我沮丧的是我的handelbars模板中的范围,我只是简单地打开和关闭范围。

{{#info}}
  <h1>{{header}}</h1>
  ...
{{/info}}
  {{#if query.country}}
    <h2>Welcome to the {{query.country}}!</h2>
  {{else}}
    <h2>Welcome!</h2>
  {{/if}}
{{#info}}
  ... continue
{{/info}}

希望这有帮助。