首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Groovy-18.模板引擎

Groovy-18.模板引擎

作者头像
悠扬前奏
发布2019-05-30 20:19:35
8620
发布2019-05-30 20:19:35
举报

字符串中的简单模板

$可以用于分配的值替换

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()
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.05.30 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 字符串中的简单模板
  • 简单的模板引擎-SimpleTemplateEngine
  • 闭包创建模板-StreamingTemplateEngine
  • XML文件的模板-XMLTemplateEngine
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档