模板引擎概述
1、模板技术:从模型中分离视图的一种手段,可以降低应用程序的维护成本
2、Java语言具有Velocity和FreeMarker等
3、模板引擎与XSLT很类似
4、可以创建一个模板,包含一些占位符,在运行时替换为实际的值。模板引擎然后可以通过读取该模板并在这些占位符和运行时的值之间家里映射来实现对模板的转换。
5、
定义模板toy_xml.template
<toy>
<toyName>${toyName}</toyName>
<unitPrice>${unitPrice}</unitPrice>
</toy>
${} ->就是占位标示符,{}中的是占位符参数
实例化模板
1、
import groovy.text.Template
import groovy.text.SimpleTemplateEngine
import java.io.File
class ToyTemplateOutXml{
static void main(args){
def file = new
File('toy_xml.template')
def binding= ['toyName':'toy1',unitPrice:'100']
def engine = new SimpleTemplateEngine()
def template = engine.createTemplate(file).make(binding)
prinltn template.toString()
}
}
例子1:
1、toy_html.template
<html>
<head>
<title>${title}>/title>
</head>
<body>
<talbe>
<th>Toy Name</th><th>Unit Price</th>
<%for(toy in toys){%>
<tr>
<td>${toy.toyName}</td>
<td>${toy.unitPrice}</td>
</tr>
<%}%>
</table>
</body>
</html>
2、ToyTemplateOutHtml.groovy
class ToyTemplateOutHtml{
static void main(args){
def toys=[]
def file = new File('toy_html.template')
def toy1= new Toy(toyName:'toy1',unitPrice:'100')
def toy2= new Toy(toyName:'toy2',unitPrice:'200')
def toy3= new Toy(toyName:'toy3',unitPrice:'300')
toys <<toy1<<toy2<<toy3
def binding =['toys':toys,'title':'Display Toy!']
def engine = new SimpleTemplateEngine()
def template = engine.createTemplate(file).make(binding)
println template.toString()
def outHtml = new File('toy.html')
if(outHtml.exists()){
outHtml.delete()
}
outHtml.append(template)
}
}
例子2:
1、toy_html_sql.template
<html>
<head>
<title>${title}</title>
</head>
<body>
<table>
<th>Toy Name</th><th>Unit Price</th>
<%sql.eachRow("select * from toys"){toy -> %>
<tr>
<td>${toy.toyName}</td>
<td>${toy.unitPrice}</td>
</tr>
<%}%>
</table>
</body>
</html>
2、ToyTemplateSqlOutHtml.groovy
class ToyTemplateSqlOutHtml{
static void main(args){
def file = new File('toy_html_sql.template')
def db = '...' ; def user = '...' ; def password = '...' def driver = '...'
def sql = Sql.newInstance(db,user,password,driver)
def binding = ['sql': sql , 'title':'Display Toy!']
def template = engine.createTemplate(file).make(binding)
println template.toString()
def outHtml = new File('toy.html')
if(outHtml.exists()){
outHmlt.delete()
}
outHtml.append(template)
}
}