小胡子:如何在Java中创建自定义辅助函数

问题描述 投票:0回答:2

我将Mustache Template Engine in JavaSpring 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;
      }
  }
java spring-mvc mustache
2个回答
0
投票

个人,我做类似...

 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}}


-1
投票

您可以在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}}

{/行}

© www.soinside.com 2019 - 2024. All rights reserved.