Velocity template engine

Introduction to velocity

  1. Introduction to velocity
    Velocity is a Java-based template engine that can obtain data in Java objects through specific syntax and fill it into templates, thus achieving the separation of interface and Java code.
    image.png
  2. Application scenarios
  • Web application: As a view for the application, data is displayed.
  • Source code generation: Velocity can be used to generate Java source code based on templates
  • Automated Emails: Email Templates for Website Registration, Authentication, and More
  • Web page staticization: generate static web pages based on velocity template
  1. velocity structure
    image.png

Velocity is mainly divided into app, context, runtime and some auxiliary util parts.

  • app module: It mainly encapsulates some interfaces and exposes them to users. There are two main classes, namely Velocity (single case) and VelocityEngine.
  • Context module: mainly encapsulates the variables needed for template rendering
  • Velocity is mainly divided into app, context, runtime and some auxiliary util parts.
  • Runtime module: The core module of the entire Velocity. The Runtime module will parse the loaded template into a syntax tree. When Velocity calls the mergeTemplate method, it will render the entire tree and output the final rendering result.
  • The RuntimeInstance class provides a singleton mode for the entire velocity rendering. Once you get this instance, you can complete the rendering process.

Quick Start

1. Requirements analysis

Use velocity to define an html template and fill dynamic data into the template to form an html

2. Implementation steps

  1. Create maven project
    image.png
  2. Introduce dependencies
 <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
  1. Create a new directory vms, then create a new html template with a suffix name renamed vm
    image.png
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>velocity_01</title>
</head>
<body>
hello,${name}
</body>
</html>
  1. Write test class to generate template file
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.junit.Test;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;

public class velocity01 {<!-- -->
    @Test
    public void test01() throws IOException {<!-- -->
        //1.Set the resource loading class of velocity
        Properties prop = new Properties();
        prop.put("file.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        //2. Load velocity engine
        Velocity.init(prop);
        //3. Load the velocity container
        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put("name","velocity");
        //4. Load velocity template
        Template template = Velocity.getTemplate("vms/01-quikstart.vm", "utf-8");
        //5. Merge data
        FileWriter fileWriter = new FileWriter("D:\soft\software\work\\velocity\velocity_01\src\ main\resources\html\01-quikstart.html");
        template.merge(velocityContext,fileWriter);
        //6. Release resources
        fileWriter.close();
    }
}

image.png

Basic syntax

VTL introduction

Velocity Template Language (VTL), a template language provided in Velocity, aims to provide the simplest and cleanest way to incorporate dynamic content into web pages. Simply put, VTL can display dynamic numbers in the program to the web page.

VTL statements are divided into four categories: Comments, Non-parsed content, References and instructions.

VTL annotation
Grammar
  1. Line comments
## Line comment content
  1. block comments
#*
Block comment content 1
Block comment content 2
*#
  1. Documentation comments
#**
Document comment content 1
Document comment content 2
**#
Example
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>velocity_01</title>
</head>
<body>
## Line comment content

#*
Block comment content 1
Block comment content 2
*#

#**
Document comment content 1
Document comment content 2
**#
</body>
</html>
Non-resolved content

The so-called non-parsed content is content that will not be parsed by the engine.

Grammar
#[[
Non-parsed content 1
Non-parsed content 2
]]#
Example
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>velocity_01</title>
</head>
<body>
#[[
Non-parsed content 1
Non-parsed content 2
]]#
</body>
</html>
Quote
Variable reference
Grammar

The reference statement operates on the properties in the engine context object. Grammar is divided into regular grammar (attributes) and regular grammar (attributes) and regular grammar (attributes) and regular grammar ({attributes}).

$Variable name, if there is no corresponding variable in the context, the string "$Variable name" will be output
${<!-- -->Variable name}, if there is no corresponding variable in the context, the string ""${<!-- -->Variable name}"

$!Variable name, if there is no corresponding variable in the context, an empty string "" will be output.
$!{<!-- -->Variable name}, if there is no corresponding variable in the context, an empty string "" will be output.
Example
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Variable reference</title>
</head>
<body>
General syntax: $name
Regular syntax: ${name}
##$Variable name, if there is no corresponding variable in the context, the string "$Variable name" will be output.
##${Variable name}, if there is no corresponding variable in the context, the string ""${Variable name}" will be output.
##$!Variable name, if there is no corresponding variable in the context, an empty string "" will be output.
##$!{Variable name}, if there is no corresponding variable in the context, the empty string "" will be output.
General syntax: $!name
Regular syntax: $!{name}
</body>
</html>
package com.JokerDJ.VelocityTest;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.junit.Test;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;


public class velocity02 {<!-- -->
    @Test
    public void test01() throws IOException {<!-- -->
        //1.Set the resource loading class of velocity
        Properties prop = new Properties();
        prop.put("file.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        //2. Load velocity engine
        Velocity.init(prop);
        //3. Load the velocity container
        VelocityContext velocityContext = new VelocityContext();
// velocityContext.put("name","velocity");
        //4. Load velocity template
        Template template = Velocity.getTemplate("vms/02-cite-variable reference.vm", "utf-8");
        //5. Merge data
        FileWriter fileWriter = new FileWriter("D:\soft\software\work\\velocity\velocity_01\src\ main\resources\html\02-cite-variable reference.html");
        template.merge(velocityContext,fileWriter);
        //6. Release resources
        fileWriter.close();
    }
}

Output content
image.png

Attribute reference
Grammar
$Variable name.Attribute. If there is a corresponding variable in the context, the string "$Variable name.Attribute" will be output.
${<!-- -->Variable name.Attribute} If there is no corresponding variable in the context, the string "${Variable name.Attribute}" will be output.
$!Variable name. If there is no corresponding variable in the context, the string "" will be output.
$!{<!-- -->Variable name.Attribute} If there is no corresponding variable in the context, the string "" will be output.
Example
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Variable reference</title>
</head>
<body>
General syntax: $user.username
Regular syntax: ${user.username}

General syntax: $!user.username
Regular syntax: $!{user.username}
</body>
</html>
package com.JokerDJ.VelocityTest;

import com.JokerDJ.VelocityTest.Pojo.user;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.junit.Test;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;


public class velocity03 {<!-- -->
    @Test
    public void test01() throws IOException {<!-- -->
        //1.Set the resource loading class of velocity
        Properties prop = new Properties();
        prop.put("file.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        //2. Load velocity engine
        Velocity.init(prop);
        //3. Load the velocity container
        user user = new user();
        user.setUsername("Zhang San");
        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put("user",user);
        //4. Load velocity template
        Template template = Velocity.getTemplate("vms/03-cite-attribute reference.vm", "utf-8");
        //5. Merge data
        FileWriter fileWriter = new FileWriter("D:\soft\software\work\\velocity\velocity_01\src\ main\resources\html\03-cite-attribute reference.html");
        template.merge(velocityContext,fileWriter);
        //6. Release resources
        fileWriter.close();
    }
}

image.png

Method reference

Method reference actually refers to the method calling operation, focusing on return value and parameters. The return value of the method will be output to the final result.

Grammar
$Variable name.Method ([parameter 1[, parameter 2]*]?), conventional writing method
${<!-- -->Variable name.Method ([parameter 1[, parameter 2]*]?)}, formal writing
$!Variable name.Method ([parameter 1[, parameter 2]*?), conventional writing method
$!{<!-- -->Variable name.Method ([parameter 1[, parameter 2]*]?)}, formal writing
Example
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Method reference</title>
</head>
<body>
General syntax: $str.split(",")-------$now.getTime()
Regular syntax: ${str.split(",")}-------${now.getTime()}

General syntax: $!str.split(",")-------$!now.getTime()
Regular syntax: $!{str.split(",")}-------$!{now.getTime()}
</body>
</html>
package com.JokerDJ.VelocityTest;

import com.JokerDJ.VelocityTest.Pojo.user;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.junit.Test;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;


public class velocity04 {<!-- -->
    @Test
    public void test01() throws IOException {<!-- -->
        //1.Set the resource loading class of velocity
        Properties prop = new Properties();
        prop.put("file.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        //2. Load velocity engine
        Velocity.init(prop);
        //3. Load the velocity container
        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put("str","hello,Velocity");
        velocityContext.put("now",new Date());
        //4. Load velocity template
        Template template = Velocity.getTemplate("vms/04-cite-method reference.vm", "utf-8");
        //5. Merge data
        FileWriter fileWriter = new FileWriter("D:\soft\software\work\\velocity\velocity_01\src\ main\resources\html\04-cite-method reference.html");
        template.merge(velocityContext,fileWriter);
        //6. Release resources
        fileWriter.close();
    }
}

Directives

set

Function: Define variables on the page
Syntax: #set($variable=value)
Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Method reference</title>
</head>
<body>
#set($str="hello word")
#set($int=10)
#set($arr=[1,2,3])
#set($boolean=true)
#set($maps={"key1":"value1","key2":"value2"})

## You can also reference variables when declaring them again.
#set($name="JokerDJ")
#set($map={"key1":$!{name},"key2":"value2"})
## Reference variable acquisition
String: $!{str}
Numeric type: $!{int}
Boolean type: $!{boolean}
Array type: $!{arr}
map.key1:$!{map.key1}
map.key2:$!{map.key2}
</body>
</html>
package com.JokerDJ.VelocityTest;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.junit.Test;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;


public class velocity05 {<!-- -->
    @Test
    public void test01() throws IOException {<!-- -->
        //1.Set the resource loading class of velocity
        Properties prop = new Properties();
        prop.put("file.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        //2. Load velocity engine
        Velocity.init(prop);
        //3. Load the velocity container
        VelocityContext velocityContext = new VelocityContext();
        //4. Load velocity template
        Template template = Velocity.getTemplate("vms/05-set command.vm", "utf-8");
        //5. Merge data
        FileWriter fileWriter = new FileWriter("D:\soft\software\work\\velocity\velocity_01\src\ main\resources\html\05-set directive.html");
        template.merge(velocityContext,fileWriter);
        //6. Release resources
        fileWriter.close();
    }
}

image.png

if/elseif/else

Function: Make logical judgments
grammar

#if (judgment condition)
....
#elseif (judgment condition)
....
#else
....
#end

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Method reference</title>
</head>
<body>
#set($lag="Java")
#if($lag.equals("Java"))
java development engineer
#elseif($lag.equals("PHP"))
PHP development engineer
#else
Development Engineer
#end
</body>
</html>
package com.JokerDJ.VelocityTest;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.junit.Test;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;


public class velocity06 {<!-- -->
    @Test
    public void test01() throws IOException {<!-- -->
        //1.Set the resource loading class of velocity
        Properties prop = new Properties();
        prop.put("file.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        //2. Load velocity engine
        Velocity.init(prop);
        //3. Load the velocity container
        VelocityContext velocityContext = new VelocityContext();
        //4. Load velocity template
        Template template = Velocity.getTemplate("vms/06-if directive.vm", "utf-8");
        //5. Merge data
        FileWriter fileWriter = new FileWriter("D:\soft\software\work\\velocity\velocity_01\src\ main\resources\html\06-if directive.html");
        template.merge(velocityContext,fileWriter);
        //6. Release resources
        fileWriter.close();
    }
}
foreach

Function: Traverse the loop array or collection
grammar

#foreach($item in $items)
...
[#break]
#end
  • $items: object or collection that requires variables
  • $item: variable name, each item of the variable
  • [#break]:Exit the loop
  • Built-in properties
    1. f o r e a c h . i n d ex : Get the convenient index, starting from 0 2. foreach.index: Get the convenient index, starting from 0 2. foreach.index: Get the convenient index, starting from 0 2. foreach.count: Get the number of traversals , starting from 1

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
#foreach($item in $strs)
$item
#end

#foreach($item in $users)
    $item.username
#end
</body>
</html>
package com.JokerDJ.VelocityTest;

import com.JokerDJ.VelocityTest.Pojo.user;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.junit.Test;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;


public class velocity07 {<!-- -->
    @Test
    public void test01() throws IOException {<!-- -->
        //1.Set the resource loading class of velocity
        Properties prop = new Properties();
        prop.put("file.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        //2. Load velocity engine
        Velocity.init(prop);
        //3. Load the velocity container
        VelocityContext velocityContext = new VelocityContext();
        String[] strs = {<!-- -->"Apple", "Samsung", "Xiaomi", "Huawei"};
        List<user> users = new ArrayList<>();
        users.add(new user("Xiao Ming"));
        users.add(new user("小蓝"));
        users.add(new user("小红"));

        velocityContext.put("strs",strs);
        velocityContext.put("users",users);
        //4. Load velocity template
        Template template = Velocity.getTemplate("vms/07-foreach directive.vm", "utf-8");
        //5. Merge data
        FileWriter fileWriter = new FileWriter("D:\soft\software\work\\velocity\velocity_01\src\ main\resources\html\07-foreach directive.html");
        template.merge(velocityContext,fileWriter);
        //6. Release resources
        fileWriter.close();
    }
}

image.png

Introducing resources

include

Function: Introduce external resources. The imported resources will not be parsed by the engine.
Syntax:#include(resource)
Resource can be a string in single quotes or double quotes, or it can be a **$ variable**, the content of which is an external resource path. Note: If the path is a relative path, the file loader loading path configured by the engine is used as a reference.

Example

<! DOCTYPE html>
<html 1ang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title></head>
<body>
#include("demo8 . vm")
</body>
</html>
parse

Function: Introduce external resources, and the imported resources will be parsed by the engine
Syntax:#parse(resource)
Resource can be a string in single quotes or double quotes, or it can be a **$ variable**, the content of which is an external resource path. Note: If the path is a relative path, the file loader loading path configured by the engine is used as a reference.
Example

<! DOCTYPE html>
<html 1ang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title></head>
<body>
#parse("demo8 . vm")
</body>
</html>
define

Function: Define reuse modules (without parameters)
grammar:

#define($module name)
Module content
#end

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
#define($table)
    <table>
        ...
    </table>
#end

## Reference the defined module
    $table
</body>
</html>

evaluate

Function: dynamic calculation, dynamic calculation allows us to use variables in strings
Syntax: #evalute(“calculation statement”)

< ! DOCTYPE htm1>
<html 1ang="en ">
<head>
    <meta charset="UTF-8">
    <title>Title</title></head>
body>
<h1>Dynamic calculation</h1>
#set($name = "over")
#evaluate("#if($name== 'over' ) over #else not over #end")
#if($name=='over')
over
#else
not over
#end
</body>
</html>

Macros

Function: Define reusable modules (can take parameters)
Definition syntax

#macro(macro name[$arg]?)
...
#end

call method

$Macro name([$arg]?)

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
#macro($table $list)
    <table>
        $list
    </table>
#end

## Reference the defined module
    $table($list)
</body>
</html>