Node.js 快速手柄:获取当前URL查询并将查询传递给模板?
目前,我已经设置好了,我正在尝试获取当前的URL,提取GET查询,并在助手函数中将其传递给我的Handlebar模板。我很难找到一种方法来传递发送给我的Handlebar助手的请求,因为我似乎只能访问路由中的当前URLNode.js 快速手柄:获取当前URL查询并将查询传递给模板?,node.js,express,handlebars.js,Node.js,Express,Handlebars.js,目前,我已经设置好了,我正在尝试获取当前的URL,提取GET查询,并在助手函数中将其传递给我的Handlebar模板。我很难找到一种方法来传递发送给我的Handlebar助手的请求,因为我似乎只能访问路由中的当前URL app.get('/somewhere', function(req, res) { console.log(req.originalUrl); <-- prints the URL I am at such as somewhere?country=US res.
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'
]
});
});
然后我可以在我的车把文件中找到它。我希望我的模板能够智能地打印一些东西,但如果我收到某个请求,请打印另一个东西。大概是
{{#if currentURL.query == 'US' }}
<h1>Welcome to US!</h1>
{{else}}
<h1>Welcome to wherever the hell you are from!</h1>
{{/if}}
{{{#if currentURL.query=='US'}
欢迎来到我们这里!
{{else}
欢迎来到你来自地狱的任何地方!
{{/if}
我不确定我是不是走错了路。我了解到你可以处理某些GET请求并基于它们呈现特定页面,但我真的只想更改我的Handlebar模板文件中的一个小东西,所以我希望我不必为我要处理的每个GET请求创建多个Handlebar模板。或者这是正确的方法?所以我想起来了。真傻。我在模板中定义了一个作用域,因此它只能访问
info
变量
{{#info}}
<h1>{{header}}</h1>
...
{{/info}}
由于把手的工作原理,您可以简单地将上下文添加到渲染函数中。然后它就可以使用了
让我绊倒的是范围,尽管在我的handelbars模板中,我只是简单地打开和关闭范围
{{#info}}
<h1>{{header}}</h1>
...
{{/info}}
{{#if query.country}}
<h2>Welcome to the {{query.country}}!</h2>
{{else}}
<h2>Welcome!</h2>
{{/if}}
{{#info}}
... continue
{{/info}}
{{{#info}
{{header}}
...
{{/info}
{{{if query.country}
欢迎来到{{query.country}!
{{else}
欢迎
{{/if}
{{{#info}
... 持续
{{/info}
希望这有帮助
app.get('/info', function(req, res) {
//set context of handlebars
res.render('info', {
info : {
header : "View Title"
},
query : req.query
}
}
{{#info}}
<h1>{{header}}</h1>
...
{{/info}}
{{#if query.country}}
<h2>Welcome to the {{query.country}}!</h2>
{{else}}
<h2>Welcome!</h2>
{{/if}}
{{#info}}
... continue
{{/info}}