TemplateUtil

Introduction

With the popularity of frontend and backend separation, JSP technology and template engines are slowly becoming less important. However, in certain scenarios such as email templates and page staticization, they are still irreplaceable. Various template engine syntaxes differ greatly, and their usage methods are not the same, making the learning cost high. Hutool aims to encapsulate the commonalities of various engines, allowing users to focus only on the template syntax and reducing the learning cost.

The engines currently encapsulated by Hutool include:

Principle

Similar to the idea of Java log facades, Hutool abstracts the rendering of template engines into two concepts:

  • TemplateEngine: Encapsulates the template object and configures various settings.
  • Template: Cooperates with parameters to generate content.

By implementing these two interfaces, users can render templates while ignoring the template implementation. Hutool will also automatically select which engine to use for rendering based on the user’s introduced template engine library jar through TemplateFactory.

Usage

Rendering content from a string template

// Automatically select the engine to use based on the user's introduced template engine library jar
// TemplateConfig is the configuration for the template engine, including options such as character encoding, template path, and template loading method. By default, it renders through the template string.
TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig());

// Assuming we have introduced the Beetl engine, then:
Template template = engine.getTemplate("Hello ${name}");
// Dict is essentially a Map, which can be used here
String result = template.render(Dict.create().set("name", "Hutool"));
// Output: Hello Hutool

In other words, after using Hutool, regardless of which template engine you use, the code remains the same (only the template content changes).

Rendering from a template found in the classpath

Simply modify the TemplateConfig configuration file content to switch (here using Velocity as an example):

TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("templates", ResourceMode.CLASSPATH));
Template template = engine.getTemplate("velocity_test.vtl");
String result = template.render(Dict.create().set("name", "Hutool"));

Other ways to find templates

The way to find templates is defined by ResourceMode, including:

  • CLASSPATH: Load templates from the ClassPath.
  • FILE: Load templates from the local File directory.
  • WEB_ROOT: Load templates from the WebRoot directory.
  • STRING: Load templates from the template text.
  • COMPOSITE: Composite loading template (attempt to find templates from File, ClassPath, Web-root, and String methods respectively).