Search code examples
handlebars.jsassemblegrunt-assemble

Get current url query string


I'm trying to write a handlebars helper that spits out the current url query string. I will then use that query string to populate a template. I'm using assemble to do the html file generation.

My urls look like this: groups/group-details/?id=1 and I want to get at the id value.

Here is my helper:

Handlebars.registerHelper('currentId', function() {
    return document.location.search.split('?')[1].split('=')[1];
});

And I am calling it in my .hbs template like this:

{{currentId}}

I am expecting it to just spit out 1 in this example but nothing is shown.

Where am I going wrong?

- Edit -

Digging around in the web inspector console shows my helper is registered but if I put a breakpoint on the return statement, it never gets hit. I assume the helper just isn't being 'executed'.


Solution

  • If you're creating the html with assemble, then assemble is doing a render pass with Handlebars. This render pass would try to resolve the {{currentId}} template on the server.

    If it's doing that, I would expect an error inside the helper since document.location.search is not available. Since you aren't getting an error there, I'm assuming that the helper isn't registered with assemble and only with your front-end instance of Handlebars. If it's not registered with assemble, then {{currentId}} is interpreted as a value by Handlebars and renders nothing.

    TL;DR;

    When mixing front-end templates and backend templates, you need to escape the front-end templates so the backend process doesn't render them. Try using \{{currentId}} to see if the helper is used.