【问题标题】:Escaping curly brackets standing next to expression in handlebars转义大括号站在车把中的表情旁边
【发布时间】:2018-08-25 19:55:20
【问题描述】:

无法理解如何转义位于handlebars java templating engine 的表达式旁边的 { 或 } 符号。

我正在使用车把模板来生成纯文本,因此我不能按照 there 的建议使用 HTML ASCII 代码。

我需要像\{{{variable.name}}\} 这样的表达式来解析为{variable.value}。我应该为此创建助手还是有更清洁的方法?

【问题讨论】:

    标签: handlebars.js handlebars.java


    【解决方案1】:

    这里有一些转义的例子。最后一个方法使用助手转义(当其他方法不可用时)。

    $(document).ready(function () {
      var context = {
        "textexample1" : "hello",
        "textexample2" : "<div><b>hello</b></div>",
        "textexample3" : "{ 'json' : 'sample }"
      };
      Handlebars.registerHelper('surroundWithCurlyBraces', function(text) {
        var result = '{' + text + '}';
        return new Handlebars.SafeString(result);
      });
    	var source   = $("#sourceTemplate").html();
      var template = Handlebars.compile(source);
      var html    = template(context);
      $("#resultPlaceholder").html(html);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script id="sourceTemplate" type="text/x-handlebars-template">
    Simple text : {{textexample1}}<br/>
    Html text not escaped : {{textexample2}}<br/>
    Html text escaped : {{{textexample2}}}<br/>
    Json text : {{textexample3}}<br/>
    Non JSON text with surrounding mustaches {} : { {{textexample1}} }<br/>
    Non JSON text with surrounding mustaches (no space)  : &#123;{{textexample1}}&#125;<br/>
    Solution with helper : {{#surroundWithCurlyBraces textexample1}}{{/surroundWithCurlyBraces}}
    </script>
    <br/>
    <div id="resultPlaceholder">
    </div>

    【讨论】:

    • 我不能在周围的胡须和双括号之间添加空格或其他字符。模板应准确解析为 {variable.value}
    • 我为您添加了一个解决方案:使用 {} 的 html 代码({ 和 })。答案已相应更新
    • 我不能使用 HTML ASCII。我在问题中指定了它。这是纯文本生成器,因此模板解析后没有其他渲染。
    • 我已经用一个使用助手的解决方案再次更新了答案。
    • 谢谢!我已经有了一个带有助手的解决方案,但它看起来对我来说是开销。仍在寻找更简单的解决方案。没有简单的方法来逃避模板中的符号是失望
    【解决方案2】:
    {{myvar}}{{append '' '}'}}
    

    从这里添加助手: https://www.npmjs.com/package/handlebars-helpers#string

    【讨论】:

    • 丑得要命,但有效。
    【解决方案3】:

    我碰到了这个。

    最后,添加辅助函数是最简单的解决方案。

    我增强了@Christophe 建议的解决方案,因为我还需要给定参数的驼峰式版本:

    Handlebars.registerHelper('surroundWithCurlyBraces', function(text, camelCase) {
      
      return new Handlebars.SafeString(surroundWithCurlyBraces(camelCase? _.camelCase(text): text));
    });
    

    那么你可以这样称呼它:

    {{surroundWithCurlyBraces variable.name}}
    

    或者 - 如果你需要 camelCase

    {{surroundWithCurlyBraces variable.name true}}
    

    【讨论】:

      猜你喜欢
      • 2018-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 2018-07-06
      相关资源
      最近更新 更多