【问题标题】:Assign value to a locals variable in keystonejs为keystonejs中的局部变量赋值
【发布时间】:2018-02-14 18:31:22
【问题描述】:

在 keystonejs(一个节点 cms)中,我使用把手作为 keystonejs 中的模板引擎。在车把文件中,我使用 #each 来遍历数组。

 {{#each data.positions}}
      <h1 onclick = "callFunction()"> {{title}} </h1>
 {{/each}}

这里我想在路由中调用一个函数,我该怎么做?

我想到的其他方式来初始化本地变量。就像我在路由文件中有一个变量 locals.selectedPositionIndex 一样,我想在单击任何 h1 元素时将特定 h1 元素的 @index 值分配给该变量。

【问题讨论】:

    标签: javascript node.js handlebars.js keystonejs


    【解决方案1】:

    您可以在 Handlebars 模板的底部包含一个脚本并在其中包含该函数:

    <script>
      document.querySelector('h1').addEventListener('click', function() {
        // Code here
      })
    </script>
    

    或者,这里有一个有用的答案: Passing a function into a Handlebars template

    我已修改上述问题的答案以使用 KeystoneJS:

    在您看来,您可以将您的功能分配给本地人

    locals.func = function () {
      // Code here
    };
    

    然后你需要在 /templates/views/helpers/index.js 中创建一个 Handlebars 助手

    _helpers.stringifyFunc = function(fn) {
      return new hbs.SafeString("(" + fn.toString().replace(/\"/g,"'") + ")()");
    };
    

    然后您可以在 Handlebars 模板中使用它:

    <h1 onclick="{{ stringifyFunc func }}">{{ title }}</h1>
    

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-05
      • 2013-08-02
      • 2011-11-06
      相关资源
      最近更新 更多