velocity learning (2)--VTL grammar

Notes

Single-line comments are ##, multi-line comments are #* *# , and the commented content will not be parsed by the template engine. The documentation comments are as follows:

#**
*@author xxx
*@version 5
*#

References to variables, properties, and methods

VTL can reference variables, properties, and methods. When displaying a variable, output its toString method. This is similar to System.out.print(). When outputting a property, the property must be accessible, or its get method is accessible, and referencing a method will display the output of the method.

Case:

person entity class

package com.wuk.entity;

public class Person {

    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }

    public String sayHello(String say){

        return say+"is a boy";
    }
}

DemoServlet.java

package com.wuk.velocity;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wuk.entity.Person;


@WebServlet("/DemoServlet")
public class DemoServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doPost(request,response);
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Person person=new Person();
        person.setAge(12);
        person.setName("wuk");
        request.setAttribute("person", person);
        request.getRequestDispatcher("/WEB-INF/hello.vm").forward(request, response);
    }

}

hello.vm

<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>Test Velocity</title>
</head>
<body>
<p>$person</p>
<p>$person.name</p>
<p>$person.toString()</p>
<p>$person.sayHello("wuk")</p>
</body>
</html>

From this case, it can be seen that not only the object can be called in the velocity page, but also the method of the object can be called directly, and even parameters can be passed.


#set()的用法

In addition to being able to reference an object instance like $person , you can also use #set() to set an object in the template context.

#set($person = "Tom")
$person

You can also set a List or Map object, and you can call its get(), isEmpty() and other methods

##设置list集合对象
#set($l=["a", "b", "c"])
##设置Map集合对象
#set($s={"a":"aaa", "b":"bbb", "c":"ccc"})
<p>$l.get(1)</p>
<p>$l.isEmpty()</p>
<p>$s.get("a")</p>

Output result:

b
false
aaa

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

#set($a = 10)
#if($a > 0)
    <p>bigger than 0</p>
#elseif($a > 5)
    17
    <p>bigger than 5</p>
#elseif($a == 10)
    <p>equals to 10</p>
#else
    <p>others</p>
#end

The judgment can only compare variables of the same type. If the variable types at both ends of == are different, it will directly return false. For string types, return true if the string content is the same. For the type passed in by the servlet, such as a JavaBean called User, the comparison is actually calling its equals() method, so if you can override the User's equals() and hashCode() methods to change the behavior of the judgment.
for example:

#set($a="aaa")
#set($b="aaa")
#if($a==$b)
<p>true</p>
#end

The result is true
judgment logic can also use && || ! in Java to combine logic.

#foreach($xxx in $xxxList)...#end

Like Java, loops can use foreach. Use foreach to iterate the output List and Map.

#set($list=["a","b","c"])
#set($map={"a":"aaa","b":"bbb","c":"ccc"})

##List集合的遍历
<ul>
    #foreach($l in $list)
        <li>$l</li>
    #end
</ul>

##Map集合也可以进行循环遍历 遍历的是值
</ul>
    #foreach($m in $map)
        <li>$m</li>
    #end
</ul>

##Map集合
<ul>
    #foreach($m in $map.keySet())
        <li>$m: $map.get($m)</li>
    #end
</ul>   

During the iteration process, velocity gives a variable velocityCount to record the number of iterations. Of course, you can also define a variable to record by yourself. There is also a velocityHasNext that can be used to determine whether the iteration is complete. Examples are as follows:

##List集合的遍历
<ul>
    #foreach($l in $list)

        <li>$velocityCount</li>
        <li>$l</li>
        <li>$velocityHasNext</li>
    #end
</ul>

We can use velocityCount to produce the effect of changing the color of the grid.

##List集合的遍历
<table border="1" height="100px" width="100px"> 
            #foreach($l in $list)
              <tr style="background-color:
                #if($velocityCount%2==0)
                     #c3f3c3"
                #else
                     #f3c3f3"
                #end
              >
                <td>$l</td>
              </tr>
            #end
</table>

However, it is generally recommended that the control of layout appearance should be controlled by CSS and JS.

#include()和#parse()

#include()Both #parse()are used to import a text file, but the text introduced by #include() will not be rendered by the template engine, and #parse()a text that can be rendered is introduced.

An example is as follows:
/WEB-INF/views/module.vm

#set($list=["aaa", "bbb", "ccc"])
<ul>
#foreach($l in $list)
<li>$l</li>
#end
</ul>

/WEB-INF/views/test.vm

#include("/WEB-INF/views/module.vm")
#parse("/WEB-INF/views/module.vm")

write picture description here

#stop

This directive stops the template engine, mainly for debugging. After the template engine is stopped, nothing that follows will be output. Examples are as follows:

#set($list=["aaa", "bbb", "ccc"])
<ul>
#foreach($l in $list)
<li>$l</li>
#stop
<li>$l</li>
#end
</ul>
<p>test</p>

macro definition

If you are familiar with C language, you should know the purpose of macro definition. In C language, macro definition is the replacement of text. It can be used to set constants and even encapsulate some functions into macro definitions. The macro definition of velocity is also a text replacement, but the writing method is more similar to directly defining the function .

Examples are as follows:

##宏的定义
#macro(show_table $list)
    <table border="1" height="100px" width="100px"> 
            #foreach($l in $list)
              <tr style="background-color:
                #if($velocityCount%2==0)
                     #c3f3c3"
                #else
                     #f3c3f3"
                #end
              >
                <td>$l</td>
              </tr>
            #end
    </table>
#end

#set($list=["a","b","c","e"])
##宏的引用
#show_table($list)

#set($list1=["1","2","3","4"])
#show_table($list1)

Through macro definitions, we can extract some common parts for encapsulation and reuse. The parameters declared by the macro definition can be variables, Lists, Maps, basic Java types and strings.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325588806&siteId=291194637