【问题标题】:Express-Handlebars: Getting current URL query and passing query to a template?Express-Handlebars:获取当前 URL 查询并将查询传递给模板?
【发布时间】:2014-12-21 14:47:19
【问题描述】:

目前我已经设置了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'
    ]
  });
});

我希望编写一个辅助函数,可以利用节点的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 请求。或者也许这是正确的做法?

【问题讨论】:

    标签: node.js express handlebars.js


    【解决方案1】:

    所以我想通了。很傻。我在模板中定义了一个范围,因此它只能访问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 的工作原理,您可以简单地向渲染函数添加上下文。然后就可以使用了。

    让我绊倒的是示波器,但在我的手把模板中,我只是简单地打开和关闭示波器。

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

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2017-01-12
      • 2019-02-05
      • 2014-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-31
      • 1970-01-01
      • 2021-02-25
      相关资源
      最近更新 更多