首页 > 其他 > 详细

18 使用模板引擎

时间:2016-07-29 18:28:01      阅读:203      评论:0      收藏:0      [点我收藏+]

1       使用模板引擎

模板存放的只是文本。模板能包括引用变量和groovy代码。groovy的模板引擎提供了createTemplate 方法来实现Strings, Files, Readers or URL,返回的是Template 对象。

Template 对象通常用来创建最终的文本。Template 调用make方法,返回的是Writable,而make方法中传入的是键值对的map,而该map是传入模板的变量名及对应的值。

package template

 

import groovy.text.SimpleTemplateEngine

 

class TemplateTest {

 

    static main(args) {

       String templateText = ‘‘‘Project report:

          

          

           We have currently ${tasks.size} number of items with a total duration of $duration.

           <% tasks.each{%>

              - $it.summary;

           <%}%>

       ‘‘‘;

      

       def list = [

           new Task(summary:"Learn Groovy",duration:4),

           new Task(summary:"Learn Grails",duration:12)

           ];

       def totalDuration = 0;

       list.each {totalDuration+=it.duration};

       def engine = new SimpleTemplateEngine();

       def template = engine.createTemplate(templateText);

       def binding = [

           duration:"$totalDuration",

           tasks:list

           ];

       println (template.make(binding)).toString();

    }

 

}

 

输出

Project report:

          

          

           We have currently 2 number of items with a total duration of 16.

          

              - Learn Groovy;

          

              - Learn Grails;

          

      

 

18 使用模板引擎

原文:http://www.cnblogs.com/yaoyuan2/p/5719203.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!