assign a variable in handlebars

dlavely picture dlavely · Jul 21, 2017 · Viewed 13.7k times · Source

I am working on the stencil platform on big commerce. this platform uses the handlebars syntax. I need to be able to set a value based on one of the parameters in my URL, more that like the 'window.location.pathname', and i need to be able to access this new variable across the site. I am able to make something work two different ways using regular JavaScript, but i do not want to recreate my script in every place throughout the site. So basically, I could use some help getting one of my 2 vanilla scripts into a handlebars for formatting. What i have that works is shown below:

<p id="BrandLogo"></p>
<script>
    var directory = window.location.pathname;
    var branding;
    var str = directory.includes("blackvue");
    if (str === false) {
        branding = value one;
    } else {
        branding = value 2
    }
    document.getElementById("BrandLogo").innerHTML = branding;
</script>

or

<p id="BrandLogo"></p>
<script>
    var directory = window.location.pathname;
    var branding;
    if (str == '/URL-I-Want-To-Focus-On/') {
        branding = value one;
    } else {
        branding = value 2
    }
    document.getElementById("BrandLogo").innerHTML = branding;
</script>

Thanks in advance

Answer

Dan King picture Dan King · Aug 19, 2017

If you are trying to set and use a local variable within handlebars try something like this:

First, create a helper function:

var handlebars = require('handlebars');
handlebars.registerHelper("setVar", function(varName, varValue, options) {
  options.data.root[varName] = varValue;
});

Next, set your variable(s).

{{setVar "greeting" "Hello World!"}}
{{#if some-condition}}
    {{setVar "branding" "Value one"}}
{{else}}
    {{setVar "branding" "Value 2"}}
{{/if}}

Finally, use the variable(s):

<div>
  <h1>{{greeting}}</h1>
</div>

document.getElementById("BrandLogo").innerHTML = {{branding}};