目录

Groovy - 模板引擎(Template Engines)

Groovy的模板引擎就像邮件合并一样(从数据库中自动添加名称和地址到字母和信封,以便于向许多地址发送邮件,特别是广告),但它更为通用。

简单的字符串模板

如果你采用下面的简单示例,我们首先定义一个名称变量来保存字符串“Groovy”。 在println语句中,我们使用$ symbol来定义可以插入值的参数或模板。

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

如果上面的代码在groovy中执行,将显示以下输出。 输出清楚地显示$ name被def语句指定的值替换。

简单的模板引擎

以下是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

如果上面的代码在groovy中执行,将显示以下输出。

现在让我们使用模板的XML文件。 作为第一步,我们将以下代码添加到名为Student.template的文件中。 在以下文件中,您将注意到我们尚未添加元素的实际值,而是添加了占位符。 所以$ name,$ is和$ subject都被放置为占位符,需要在运行时替换。

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

现在让我们添加我们的Groovy脚本代码来添加可用于将实际值替换为上述模板的功能。 关于以下代码,应注意以下事项。

  • 占位符到实际值的映射是通过绑定和SimpleTemplateEngine完成的。 绑定是一个Map,其中占位符为键,替换为值。

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

如果上面的代码在groovy中执行,将显示以下输出。 从输出可以看出,值已在相关占位符中成功替换。

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

StreamingTemplateEngine

StreamingTemplateEngine引擎是Groovy中另一个模板引擎。 这类似于SimpleTemplateEngine,但使用可写闭包创建模板,使其对大型模板更具可伸缩性。 特别是这个模板引擎可以处理大于64k的字符串。

以下是如何使用StreamingTemplateEngine的示例 -

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)

如果上面的代码在groovy中执行,将显示以下输出。

This Tutorial is Groovy The Topic name is Templates

XMLTemplateEngine

XmlTemplateEngine用于模板场景,其中模板源和预期输出都是XML。 模板使用普通的$ {expression}和$ variable表示法将任意表达式插入模板中。

以下是如何使用XMLTemplateEngine的示例。

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()

如果上面的代码在groovy中执行,将显示以下输出

   Joe
   1
   Physics 
↑回到顶部↑
WIKI教程 @2018