我将Mustache Template Engine in Java
与Spring mvc 3
+ Maven
结合使用,模板可以正确呈现,但是现在我想为我的网站提供一些自定义功能。假设我有300个字符,现在我只想显示50个字符,因此需要truncate
文本,并且截断内容以...
结尾。因此,为此,我必须创建一些自定义函数。所以我很困惑,如何以及在何处创建自定义助手功能。我可以在HTML页面内的标签中创建这些类型的函数,还是必须在Java类文件上创建函数。请给我一些建议。HTML模板:
<ul>
{{#items}}
<li>{{name}} : {{detail}}</li>
{{/items}}
<ul>
Javascript截断函数
function truncate(str) {
console.log(str);
if (str.length > 40) {
return str.slice(0, 40) + "...";
} else {
return str;
}
}
个人,我做类似...
private static class Scope {
public String name;
public Function<String, String> capitalize() { // the magic is here
return return (obj) -> ("_" + obj + "_").toUpperCase();
}
}
public String renderTemplate() {
MustacheFactory mf = new DefaultMustacheFactory();
Mustache mustache = mf.compile("template.mustache");
StringWriter stringWriter = new StringWriter();
Scope scope = new Scope();
scope.names = "boris";
mustache.execute(stringWriter, scope);
return stringWriter.toString();
}
带有模板..
{{#capitalize}} {{ name }} {{/capitalize}}
您可以在Moustache中使用功能。
_html=mustache.render(mytemplate,
{rows:therows,
nametruncated: function() {return 'hello from m'}
);
然后您可以在模板中使用:
<div>{{nametruncated}}</div>
现在您可以使用计数器值:
_html=mustache.render(mytemplate,
{rows:therows,
nametruncated: function() {
//you get the right member of you array
str=yourarray[counter]['mystring']
if (str.length > 40) {
return str.slice(0, 40) + "...";
} else {
return str;
}
});
在模板中
{#rows}
{{aproperty}}</br>
{{nametruncated}}
{/行}