【问题标题】:How to use Handlebars ternary helper?如何使用 Handlebars 三元助手?
【发布时间】:2015-04-03 23:36:44
【问题描述】:

this answer之后,我写了一个类似的助手

module.exports.register = function (Handlebars) {
    Handlebars.registerHelper('ternary', function(test, yes, no) {
        return test ? yes : no;
    });
};

我确定帮助程序已加载并正在定义,但无法弄清楚使用它的语法。我试过像

一样使用它
<div>{{ternary(true, 'yes', 'no')}}</div>

但这会产生assemble 构建错误

Warning: Parse error on line 10:
...<div>{{ternary(true, 'yes',
----------^
Expecting 'ID', 'DATA', got 'INVALID' Use --force to continue.

使用这样的帮助器的正确语法是什么?

【问题讨论】:

    标签: handlebars.js assemble


    【解决方案1】:

    Handlebars 助手:http://handlebarsjs.com/#helpers 不遵循模板中的 JavaScript 语法。你可以像这样使用它们:

    <div>{{ternary true "yes" "no"}}</div>
    

    【讨论】:

      【解决方案2】:

      2017 年 7 月 14 日更新

      由于这两个字符串在 JavaScript 中都被视为真值,因此我已将代码更改为以下内容:

      {{input value=email placeholder="Enter Email" class="form-control"
          disabled=(if isResetting 1 0)
      }}
      

      =============================

      原答案

      如果{{if}} 尝试使用 inline 怎么样?

      {{if user.isAdmin "True" "False" }}
      

      【讨论】:

        【解决方案3】:

        这对我有用,基于文档:https://handlebarsjs.com/guide/builtin-helpers.html#if

        {{#each langs }}
            <a class="navbar-item {{#if active}}is-active{{else}}{{/if}}" href="#{{code}}">
                {{label}}
            </a>
        {{/each}}
        

        【讨论】:

          【解决方案4】:

          在我看来,车把不够胜任吗?我试过这个(经过多次不同的尝试);

          <li class="{{#if meta.name === 'dashboard'}} active {{else}} undefined">
          

          不工作:s

          看起来你不能用字符串来做到这一点。也许只有布尔值。

          【讨论】:

          • 首先我和 Pug 一起工作了几天,但很早就看到了它的很多缺点。现在车把似乎有了自己的一些。接下来尝试...有什么建议吗? :)
          • 为此您需要一个辅助函数 - 请查看 stackoverflow.com/a/16315366/2586761 以获取示例。此外,您的示例缺少结束 {{/if}} ?。建议改为 react、vue 等 - 任何“现代”的东西。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-02-03
          • 2019-02-05
          • 1970-01-01
          • 2023-03-30
          相关资源
          最近更新 更多