Groovy笔记(11)_模板技术

模板引擎概述

 

 

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)

  }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值