Search code examples
node.jsexpresshandlebars.js

Express-Handlebars: Getting current URL query and passing query to a template?


Currently I have Express3-Handlebars set up and I'm trying to grab the current URL, extract the GET query, and pass it to my handlebars template in a helper function. I'm having trouble finding a way to pass the request sent to my handlebars helper though because I can only seem to access the current URL in my routes.

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

I was hoping to write a helper function that could utilize node's url library and pass the URL to Handlebars

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

Where I could then somehow access it in my handlebars file. I want my template to be smart to print something and but if I get a certain request, print another thing. So something like

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

Not sure if I am going about this the wrong way. I read in Express's app.get documentation you can handle certain GET requests and render specific pages based on them, but I really just want to alter one small thing in my handlebars template file so I am hoping I don't have to create multiple handlebars template for every GET request I want to handle. Or perhaps that is the proper way of going about it?


Solution

  • So I figured it out. Pretty silly. I was defining a scope within my template so it only had access to info variables.

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

    The req variable sends a query field for me to use so I ended up not needing a helper function at all. You can look up more 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
      }
    }
    

    Because of how Handlebars works, you can simply add a context to your render function. It will then be available.

    The thing that was tripping me up was the scope though so in my handelbars template, I just simply turn the scope on and off.

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

    Hope this helps.