用Groovy Template 產生代碼 2nd

來源:互聯網
上載者:User

update at 2005.7.28 upgrade 更新 Java直接調用的方式 and JSR-2

前篇:輕量級的代碼產生方案選擇

0.Groovy Template概述

    Groovy Template其實就是JSP的Groovy簡化版,而且有XPath這樣的內建xml簡化文法,並且不依賴於JSP容器,可由Java或Groovy直接調用。

   TemplateEngine的實現代碼只有219行,在src/groovy/test/SimpleTemplateEngine.java

    因為JSR-2的多行String 改用""" """而不是" " 來括住,所以 SimpleTemplateEngine暫時不可以用,可用GStringTemplateEngine暫代。

1.Groovy Template
Groovy官方網站上的連結: Groovy Templates 

Groovy Template類似JSP,不過有著動態語言的全部優勢。
IBM中文站上的《實戰Groovy: 使用Groovy 模板進行MVC 編程》

2.Groovy的內建xml文法
Groovy官方網站上的連結:  GPath

GPath是Groovy內建的XML訪問文法,很簡單,兩種典型的使用方式如下:

characters = book.character
for (c in characters)
{
        println c['@name']
 }

character = book.character.find { it['@id'] == '2' }

3.在ant裡調用groovy template
3.1 用Groovy調用template在IBM的文章裡講了。

3.2 用java直接調用template的方式如下

 SimpleTemplateEngine engine = new SimpleTemplateEngine();
 Map binding  = new HashMap();
 binding.put(....);
 String output = engine.createTemplate(templateFile).make(dataModel).toString();

4.不足:
  據同事講的
  1.模板不能用import語句,必須寫類的全路徑
  2.對 <% %>沒有方便的逸出字元
  3.xml文法裡,節點只能拿到children(),不能拿到parent()

  都不是很難的事情,相信後繼版本會改進。最慘的其實是沒有好的編輯器,想想Velocity, Freemarker遭受的待遇,GSP想很快有個好編輯器也不是這麼容易。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.