assign a variable in handlebars

情到浓时终转凉″ 提交于 2019-12-10 19:32:54

问题


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


回答1:


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}};


来源:https://stackoverflow.com/questions/45241022/assign-a-variable-in-handlebars

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!