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/