Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

javascript - assign a variable in handlebars

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...