Xou*_*boy 2 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."
}
Run Code Online (Sandbox Code Playgroud)
现在,当我渲染我的标签时,我想通过仅显示省略号后面的前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."
}
Run Code Online (Sandbox Code Playgroud)
但遗憾的是,{{my_tag}}标记未展开.Mustache手册指出:
传递的文本是文本块,未经渲染.{{tags}}不会被扩展 - lambda应该自己做.
..但我无法想象如何在不使用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."
}
Run Code Online (Sandbox Code Playgroud)
...它无声地失败(这里可能会责怪数据对象的递归使用)
有没有人知道任何其他方法来实现这一点而不诉诸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."
}
Run Code Online (Sandbox Code Playgroud)