Groovy-18.模板引擎

字符串中的简单模板

$可以用于分配的值替换

def name = "Groovy" 
println "This Tutorial is about ${name}"

简单的模板引擎-SimpleTemplateEngine

使用SimpleTemplateEngine类可以再模板中使用类似JSP的scriptlet和EL表达式,用来生成参数化文本。
模板引擎允许绑定参数列表以及值,以便可以在具有占位符的字符串中替换他们:

def text ='This Tutorial focuses on $TutorialName. In this tutorial you will learn about $Topic'  

def binding = ["TutorialName":"Groovy", "Topic":"Templates"]  
def engine = new groovy.text.SimpleTemplateEngine() 
def template = engine.createTemplate(text).make(binding) 

println template

如果使用XML文件作为模板功能,例如一个Student.template的文件中有如下内容:

<Student> 
   <name>${name}</name> 
   <ID>${id}</ID> 
   <subject>${subject}</subject> 
</Student>

然后在代码中执行:

import groovy.text.* 
import java.io.* 

def file = new File("D:/Student.template") 
def binding = ['name' : 'Joe', 'id' : 1, 'subject' : 'Physics']
                  
def engine = new SimpleTemplateEngine() 
def template = engine.createTemplate(file) 
def writable = template.make(binding) 

println writable

可以得到输出

<Student> 
   <name>Joe</name> 
   <ID>1</ID> 
   <subject>Physics</subject> 
</Student>

闭包创建模板-StreamingTemplateEngine

StreamingTemplateEngine可以使用可写的闭包创建模板,对于大模板更具可扩展性
这个引擎还可以处理大于64k的字符串。

def text = '''This Tutorial is <% out.print TutorialName %> The Topic name 

is ${TopicName}''' 
def template = new groovy.text.StreamingTemplateEngine().createTemplate(text)
  
def binding = [TutorialName : "Groovy", TopicName  : "Templates",]
String response = template.make(binding) 
println(response)

XML文件的模板-XMLTemplateEngine

XMLTemplateEngine的模板源和预期输出都是XML,也使用${expressing}和$variable表示法将表达式插入到模板中:

def binding = [StudentName: 'Joe', id: 1, subject: 'Physics'] 
def engine = new groovy.text.XmlTemplateEngine() 

def text = '''
   <document xmlns:gsp='http://groovy.codehaus.org/2005/gsp'>
      <Student>
         <name>${StudentName}</name>
         <ID>${id}</ID>
         <subject>${subject}</subject>
      </Student>
   </document> 
''' 

def template = engine.createTemplate(text).make(binding) 
println template.toString()
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,997评论 19 139
  • 本文参考自Template engines,大部分代码直接引用了文档的内容。 模板引擎介绍 Groovy语言包含了...
    乐百川阅读 7,413评论 0 5
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong阅读 22,595评论 1 92
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,148评论 1 32
  • execjs 使用 1. 安装 2. 简单使用 需要注意的是: 个别的JS语句, 用execjs返回的结果跟浏览器...
    董小贱阅读 10,824评论 1 12