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