在车把中分配变量

dla*_*ely 3 javascript handlebars.js bigcommerce

我正在大型商业上的模板平台上工作。该平台使用车把语法。我需要能够基于URL中的参数之一来设置值,更像“ window.location.pathname”之类的值,并且我需要能够跨站点访问此新变量。我可以使用常规JavaScript以两种不同的方式使某些东西工作,但是我不想在整个站点的每个地方都重新创建脚本。因此,基本上,我可以使用一些帮助将我的2个原始脚本之一放入车把以进行格式化。我有什么工作如下所示:

<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>
Run Code Online (Sandbox Code Playgroud)

要么

<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>
Run Code Online (Sandbox Code Playgroud)

提前致谢

Dan*_*ing 7

如果要在车把内设置和使用局部变量,请尝试以下操作:

首先,创建一个辅助函数:

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

接下来,设置您的变量。

{{setVar "greeting" "Hello World!"}}
{{#if some-condition}}
    {{setVar "branding" "Value one"}}
{{else}}
    {{setVar "branding" "Value 2"}}
{{/if}}
Run Code Online (Sandbox Code Playgroud)

最后,使用变量:

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

document.getElementById("BrandLogo").innerHTML = {{branding}};
Run Code Online (Sandbox Code Playgroud)

  • 因此,基本上,您建议不要使用局部变量,而是将值存储在封装的 `options.data.root[..]` 中。我正在寻找一种在 Handlebars.js 中定义局部变量的方法 (2认同)