Template Engines in Groovy – Groovy中的模板引擎

最后修改: 2019年 5月 13日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this introductory tutorial, we’ll explore the concept of template engines in Groovy.

在这个入门教程中,我们将探索Groovy中模板引擎的概念。

In Groovy, we can use GStrings to generate dynamic text easily. However, the template engines provide a better way of handling dynamic text using static templates.

在Groovy中,我们可以使用GStrings来轻松生成动态文本。然而,模板引擎提供了一种更好的方法,即使用静态模板来处理动态文本。

These templates are convenient in defining static templates for various notifications like SMS and emails.

这些模板便于为各种通知(如短信和电子邮件)定义静态模板。

2. What Is Groovy’s TemplateEngine?

2.什么是Groovy的TemplateEngine

Groovy’s TemplateEngine is an abstract class that contains the createTemplate method.

Groovy的TemplateEngine是一个抽象类,包含createTemplate方法。

All template framework engines available in Groovy extend TemplateEngine and implement createTemplate. Additionally, every engine returns the Template interface object.

Groovy中所有可用的模板框架引擎都扩展了TemplateEngine并实现了createTemplate.此外,每个引擎都返回Template接口对象。

The Template interface has a method make, which takes a map for binding variables. Therefore, it must be implemented by every template framework.

Template接口有一个方法make,它接收一个用于绑定变量的映射。因此,每个模板框架都必须实现它。

Let’s discuss the functionality and behavior of all the available template frameworks in Groovy.

让我们来讨论一下Groovy中所有可用模板框架的功能和行为。

3. SimpleTemplateEngine

3.SimpleTemplateEngine

The SimpleTemplateEngine generates dynamic text using String interpolation and scriptlets. This engine is quite useful for simple notifications like SMS and simple text emails.

SimpleTemplateEngine使用String插值和scriptlets生成动态文本。这个引擎对简单的通知(如SMS和简单的文本邮件)相当有用。

For example:

比如说。

def smsTemplate = 'Dear <% print user %>, Thanks for reading our Article. ${signature}'
def bindMap = [user: "Norman", signature: "Baeldung"]
def smsText = new SimpleTemplateEngine().createTemplate(smsTemplate).make(bindMap)

assert smsText.toString() == "Dear Norman, Thanks for reading our Article. Baeldung"

4. StreamingTemplateEngine

4.StreamingTemplateEngine

In a general sense, the StreamingTemplateEngine works similarly to SimpleTemplateEngine. However, internally it uses Writable closures to generate a template.

在一般意义上,StreamingTemplateEngine的工作方式与SimpleTemplateEngine类似。然而,在内部它使用Writable闭包来生成模板。

For the same reason, it holds benefits when working over larger Strings(> 64K). Hence, it’s more efficient than SimpleTemplateEngine.

出于同样的原因,它在处理较大的字符串(>64K)时也有好处。因此,它比SimpleTemplateEngine.更有效率。

Let’s write a quick example to generate a dynamic email content using a static template.

让我们写一个快速的例子,用一个静态模板生成一个动态的电子邮件内容。

Firstly, we’ll create a static articleEmail template:

首先,我们将创建一个静态的articleEmail模板。

Dear <% out << (user) %>,
Please read the requested article below.
<% out << (articleText) %>
From,
<% out << (signature) %>

Here, we’re using <% %> scriptlets for dynamic text and out for the writer.

在这里,我们使用<%>scriptlets作为动态文本,out作为写作者。

Now, we’ll generate the content of an email using StreamingTemplateEngine:

现在,我们将使用StreamingTemplateEngine生成一封邮件的内容。

def articleEmailTemplate = new File('src/main/resources/articleEmail.template')
def bindMap = [user: "Norman", signature: "Baeldung"]

bindMap.articleText = """1. Overview
This is a tutorial article on Template Engines...""" //can be a string larger than 64k

def articleEmailText = new StreamingTemplateEngine().createTemplate(articleEmailTemplate).make(bindMap)

assert articleEmailText.toString() == """Dear Norman,
Please read the requested article below.
1. Overview
This is a tutorial article on Template Engines...
From,
Baeldung"""

5. GStringTemplateEngine

5.GStringTemplateEngine

As the name suggests, GStringTemplateEngine uses GString to generate dynamic text from static templates.

顾名思义,GStringTemplateEngine使用GString来从静态模板生成动态文本。

Firstly, let’s write a simple email template using GString:

首先,让我们使用GString编写一个简单的email模板。

Dear $user,
Thanks for subscribing our services.
${signature}

Now, we’ll use GStringTemplateEngine to create dynamic content:

现在,我们将使用GStringTemplateEngine来创建动态内容。

def emailTemplate = new File('src/main/resources/email.template')
def emailText = new GStringTemplateEngine().createTemplate(emailTemplate).make(bindMap)

6. XmlTemplateEngine

6.XmlTemplateEngine

The XmlTemplateEngine is useful when we want to create dynamic XML outputs. It requires XML schema as input and allows two special tags, <gsp:scriptlet> to inject script and <gsp:expression> to inject an expression.

XmlTemplateEngine在我们想要创建动态XML输出时非常有用。它需要XML模式作为输入,并允许两个特殊的标签,<gsp:scriptlet>来注入脚本和<gsp:expression>来注入表达式。

For example, let’s convert the already discussed email template to XML:

例如,让我们把已经讨论过的email模板转换成XML。

def emailXmlTemplate = '''
<xs xmlns:gsp='groovy-server-pages'>
    <gsp:scriptlet>def emailContent = "Thanks for subscribing our services."</gsp:scriptlet>
    <email>
        <greet>Dear ${user}</greet>
        <content><gsp:expression>emailContent</gsp:expression></content>
        <signature>${signature}</signature>
    </email>
</xs>'''

def emailXml = new XmlTemplateEngine().createTemplate(emailXmlTemplate).make(bindMap)

Hence, the emailXml will have XML rendered, and the content will be:

因此,emailXml将有XML渲染,内容将是。

<xs>
  <email>
    <greet>
      Dear Norman
    </greet>
    <content>
      Thanks for subscribing our services.
    </content>
    <signature>
      Baeldung
    </signature>
  </email>
</xs>

It’s interesting to note the XML output is indented and beautified itself by the template framework.

有趣的是,XML的输出被模板框架缩进并美化了本身。

7. MarkupTemplateEngine

7.MarkupTemplateEngine

This template framework is a complete package to generate HTML and other markup languages.

这个模板框架是一个完整的软件包,可以生成HTML和其他标记语言。

Additionally, it uses Domain Specific Language to process the templates and is the most optimized among all template frameworks available in Groovy.

此外,它使用特定领域语言来处理模板,是Groovy中所有模板框架中最优化的。

7.1. HTML

7.1.HTML

Let’s write a quick example to render HTML for the already discussed email template:

让我们写一个快速的例子,为已经讨论过的email模板渲染HTML。

def emailHtmlTemplate = """
html {
    head {
        title('Service Subscription Email')
    }
    body {
        p('Dear Norman')
        p('Thanks for subscribing our services.')
        p('Baeldung')
    }
}"""
def emailHtml = new MarkupTemplateEngine().createTemplate(emailHtmlTemplate).make()

Therefore, the content of emailHtml will be:

因此,emailHtml的内容将是。

<html><head><title>Service Subscription Email</title></head>
<body><p>Dear Norman</p><p>Thanks for subscribing our services.</p><p>Baeldung</p></body></html>

7.2. XML

7.2 XML

Likewise, we can render XML:

同样地,我们也可以渲染XML。

def emailXmlTemplate = """
xmlDeclaration()  
    xs{
        email {
            greet('Dear Norman')
            content('Thanks for subscribing our services.')
            signature('Baeldung')
        }  
    }"""
def emailXml = new MarkupTemplateEngine().createTemplate(emailXmlTemplate).make()

Therefore, the content of emailXml will be:

因此,emailXml的内容将是。

<?xml version='1.0'?>
<xs><email><greet>Dear Norman</greet><content>Thanks for subscribing our services.</content>
<signature>Baeldung</signature></email></xs>

7.3. TemplateConfiguration

7.3.TemplateConfiguration

Note that unlike like XmlTemplateEngine, the template output of this framework is not indented and beautified by itself.

注意,与XmlTemplateEngine不同的是,这个框架的模板输出并不是自己缩进和美化的。

For such configuration, we’ll use the TemplateConfiguration class:

对于这种配置,我们将使用TemplateConfiguration类。

TemplateConfiguration config = new TemplateConfiguration()
config.autoIndent = true
config.autoEscape = true
config.autoNewLine = true
                               
def templateEngine = new MarkupTemplateEngine(config)

7.4. Internationalization

7.4.国际化

Additionally, the locale property of TemplateConfiguration is available to enable the support of internationalization.

此外,TemplateConfigurationlocale属性可用来实现对国际化的支持。

Firstly, we’ll create a static template file email.tpl and copy the already discussed emailHtmlTemplate string into it. This will be treated as the default template.

首先,我们将创建一个静态模板文件email.tpl,并复制已经讨论过的emailHtmlTemplate字符串到其中。这将被视为默认模板。

Likewise, we’ll create locale-based template files like email_ja_JP.tpl for Japanese, email_fr_FR.tpl for French, etc.

同样,我们将创建基于本地的模板文件,如日语的email_ja_JP.tpl,法语的email_fr_FR.tpl,等等。

Finally, all we need is to set the locale in the TemplateConfiguration object:

最后,我们只需要在TemplateConfiguration对象中设置locale

config.locale = Locale.JAPAN

Hence, the corresponding locale-based template will be picked.

因此,相应的基于本地的模板将被选中。

8. Conclusion

8.结语

In this article, we’ve seen various template frameworks available in Groovy.

在这篇文章中,我们已经看到了Groovy中的各种模板框架。

We can leverage these handy template engines to generate dynamic text using static templates. Therefore, they can be helpful in the dynamic generation of various kinds of notifications or on-screen messages and errors.

我们可以利用这些方便的模板引擎,使用静态模板生成动态文本。因此,它们在动态生成各种通知或屏幕上的信息和错误方面是有帮助的。

As usual, the code implementations of this tutorial are available on the GitHub project.

像往常一样,本教程的代码实现可以在GitHub项目中获得。