javascript - 限制 Mustache.js 标签呈现的字符数

标签 javascript mustache

Mustache 中有什么方法可以限制 Mustache 标签生成的字符数吗?

例如

template = "<li>{{my_tag}}</li>"

data = {
    "my_tag" : "A very long string that needs to be abbreviated to fit into the available space."
}

现在,当我呈现我的标签时,我想通过仅显示前 10 个字符后跟一个省略号来缩写长字符串。我研究了像这样使用 lambda 函数(如 Mustache 文档中所述)...

template = "<li>{{#limitLength}}{{my_tag}}{{/limitLength}}</li>"

data = {
    "limitLength" : function() {
        return function(text) {
          return text.substr(0,10) + '...';
        }
      },
    "my_tag" : "A very long string that needs to be abbreviated to fit into the available space."
}

但不幸的是,{{my_tag}} 标签没有展开。 mustache 手册指出:

The text passed is the literal block, unrendered. {{tags}} will not have been expanded - the lambda should do that on its own.

.. 但我无法想象如果不使用 Mustache.to_html() 函数如何做到这一点,当我尝试像这样使用它时......

例如

data = {
    "limitLength" : function() {
        return function(text) {
          return Mustache.to_html(text,data).substr(0,10) + '...';
        }
      },
     "my_tag" : "A very long string that needs to be abbreviated to fit into the available space."
}

...它默默地失败了(数据对象的递归使用可能是这里的罪魁祸首)

有没有人知道在不借助 javascript/jQuery 函数的情况下实现此目的的任何其他方法,如果可能的话,我想只使用 Mustache 来实现它。

最佳答案

你的函数实际上是用两个参数调用的:未渲染的文本和一个 render 函数,它可以用来渲染你的文本,保持当前上下文。

data = {
    "limitLength" : function() {
        return function(text, render) {
          return render(text).substr(0,10) + '...';
        }
      },
     "my_tag" : "A very long string that needs to be abbreviated to fit into the available space."
}

关于javascript - 限制 Mustache.js 标签呈现的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8851794/

相关文章:

javascript - Hogan JS 模板中的 For 循环

javascript - Google 的 V8 引擎真的限制每个进程 1 个 VM 吗?

javascript - 通过 Foundation Framework 有条件地提供 javascript

javascript - 如何通过拖动正确调整元素的大小?

java - 如何防止在模板中使用环境变量?

javascript - 避免模​​板代码冗余

javascript - Handlebars.js - 在表达式中连接任意字符串

javascript - ng-model 值不会在 ngModelCtrl.$commitViewValue() 上更新;

javascript - 将子元素悬停在原型(prototype)中时失去对父元素的焦点

javascript - 如何使用 jQuery 提取动态加载的 mustache 模板的一部分