模板引擎Velocity學習系列 - #set指令

#set指令

#set指令用於向一個變量或者對象賦值。apache

格式: #set($var = value)測試

LHS是一個變量,不要使用特殊字符例如英文句號等,不能用大括號括起來。測試發現#set($user.name = 'zhangsan'),#set(${age} = 18)均賦值失敗。this

RHS能夠是變量、字符串字面值、數字字面值、方法、ArrayList、Map、表達式。spa

 

測試案例code

User對象類對象

public class User {

    private String name;
    private int age;
    
    public User(String name, int age) {
        this.name = name;
        this.age = 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;
    }

}

 

 

 測試類TestVelocityblog

public class TestVelocity {

    public static void main(String[] args) {
        
        VelocityEngine engine = new VelocityEngine();
        // 初始化VelocityEngine
        engine.setProperty("resource.loader", "file");
        engine.setProperty("file.resource.loader.class",
                "org.apache.velocity.runtime.resource.loader.FileResourceLoader");
        engine.setProperty("input.encoding", "utf8");
        engine.setProperty("output.encoding", "utf8");
        engine.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, "D:\\conf");
        engine.init();

        Template template = engine.getTemplate("hellovelocity.vm");

        VelocityContext ctx = new VelocityContext();
        ctx.put("user", new User("zhangsan", 18));

        StringWriter stringWriter = new StringWriter();
        template.merge(ctx, stringWriter);
        System.out.println(stringWriter.toString());
    }
    
}

 測試模板文件 hellovelocity.vmci

#set($name = 'john') #set($age = 18) #set($array = ['a', 'b', 'c']) #set($map = {'a' : 'a', 'b' : 'b', 'c' : 'c'}) #set($userName = "$!{user.getName()}") #set($userAge = "$!{user.getAge()}") #set($userTest1 = $user.getAge_()) #set($userTest2 = "$!{user.getAge_()}")  $name $age $array.get(0) $array.get(1) $array.get(2) $map.get('a') $map.get('b') $map.get('c') $userName $userAge $userTest1 $userTest2 

輸出結果字符串


john  18  a b c a b c
zhangsan 18 $userTest1

 

說明:get

#set($userTest1 = $user.getAge_())

#set($userTest2 = "$!{user.getAge_()}")

右邊$!{user.getAge_()}表達式計算失敗狀況下,放在雙引號裏面,賦值空串,放在外面將不會賦值。

在使用#set時,字符串的字面值若是放在雙引號裏,將會被解析,放在單引號裏面,將會被當作字面量。

#set($test1 = "$userName")

#set($test2 = '$userName')

$test1=字符串zhangsan,$test2=字符串$userName。
相關文章
相關標籤/搜索