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
Because it was originally designed to generate HTML, Handlebars escapes values returned by a {{expression}} . If you don't want Handlebars to escape a value, use the "triple-stash", {{{ . Source: https://handlebarsjs.com/guide/#html-escaping.
Helpers can be used to implement functionality that is not part of the Handlebars language itself. A helper can be registered at runtime via Handlebars. registerHelper , for example in order to uppercase all characters of a string.
Handlebars doesn't allow you to write JavaScript directly within templates. Instead, it gives you helpers. These are JavaScript functions that you can call from your templates, and help you reuse code and create complex templates. To call a helper, just use it as an expression - {{helpername}} .
If you are trying to set and use a local variable within handlebars try something like this:
First, create a helper function named 'setVar':
var handlebars = require('handlebars');
handlebars.registerHelper("setVar", function(varName, varValue, options) {
options.data.root[varName] = varValue;
});
Next, set your variable(s) using the function you created in the first step.
{{setVar "greeting" "Hello World!"}}
{{#if some-condition}}
{{setVar "branding" "Value one"}}
{{else}}
{{setVar "branding" "Value 2"}}
{{/if}}
Finally, use the variable(s) on your page:
<div>
<h1 id="BrandLogo">{{greeting}}</h1>
</div>
document.getElementById("BrandLogo").innerHTML = {{branding}};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With