---
title: "StringTemplate学习笔记(二) 语法"
author: "orange5458"
date: "2011-08-21T16:11:15Z"
tags: []
categories: ["开源软件"]
slug: "stringtemplate"
draft: false
lastmod: "2011-08-21T18:39:13Z"
id: 1154463
url: "https://orange5458.iteye.com/blog/1154463"
---

一，分隔符,注释

- &lt;...&gt;貌似只能在StringTemplateGroup文件中使用
- $...$ 貌似只能在StringTemplate文件和程序中使用
- &lt;! comment !&gt;
- $! comment !$

二，保留字

 

 

default  
first  
group  
if implements  
interface  
last  
length optional  
rest  
strip  
super trunc  
else  
endif  
elseif

 

三，转义字符

- \\$ or `\<`
- &lt;\\ &gt;, `<\n>`, `<\t>`, `<\r>`

四，属性表达式

 

**表达式**  **注释**  &lt;*attribute*&gt; 如果attribute存在且不为null，输出attribute.toString(),否则输出""  &lt;i&gt;, &lt;i0&gt;, &lt;it&gt;

一般出现在&lt;attribute:template...&gt;的template中

i0和i为迭代次数的计数器，i0从0开始计数，i则从1开始计数，

而it则为当前子元素的值

&lt;*attribute*.*property*&gt;

1.如果attribute不存在，输出""

2.attribute存在，采用attribute.getProperty()/attribute.isProperty()----&gt;

   attribute.property的优先方式获取property的值value，然后输出value.toString(),

   获取value失败则报错

&lt;*attribute*.(*expr*)&gt;

同上，但是当属性名有$,&lt;特殊字符时必须使用这种方式

如：$stu.(\\"\\\\$optional\\")$

&lt;*multi-valued-attribute*&gt;

迭代输出集合子元素的toString()值(null忽略)，并将它们连接起来

注意：Map只输出key值

&lt;*multi-valued-attribute*;

null=expr0,separator=*expr1*&gt;

同上，区别在于会用expr0的值取代null，用expr1的值将子元素分割 &lt;\[*mine*, *yours,...*]&gt;

将mine和yours合并成新的集合，并且mine的元素字yours之前

（子元素类型不一致时需注意）

&lt;*template*(*argument-list*)&gt;

模板调用，argument-list为参数列表，格式为*arg-of-template*=*expr*

*其中arg-of-template为template定义中的形参名*

*expr为实参求值表达式*

&lt;*(expr)*(*argument-list*)&gt; 同上，区别在于，template的名字为expr的值 &lt;*attribute*:*template*(*argument-list*)&gt;

相当于JAVA中的attribute.template(argument-list),

与&lt;*template*(*argument-list*)&gt;类似,

区别：1.template定义中可以通过it引用attribute

         2.当attribute为集合时，迭代调用，it引用的为迭代时的子元素

&lt;*attribute*:*(expr)*(*argument-list*)&gt; 同上，区别在于，template的名字为expr的值 &lt;*attribute*:*t1*(*argument-list*): ... :*tN*(*argument-list*)&gt;

相当于JAVA中的

var result1 = attribute.t1(...);

var result2 = result1.t2(...);

...

&lt;*attribute*:{*anonymous-template*}&gt;

与&lt;*attribute*:*template*(*argument-list*)&gt;类似

{...}为匿名模板，可以使用it，也可以使用外层st中的attributes

&lt;*attribute*:{*argument-name_ | \_anonymous-template*}&gt;

同上，区别：

向匿名模板中传递了一个名为argument-name的attribute，并且attribute的value与it一致，并且此时it将失效。

&lt;*a1*,*a2*,...,*aN*:{*argument-list_ | \_anonymous-template*}&gt;

同时迭代a1...aN

迭代次数为maxLength(a1...aN)

argument-list不能省略，格式为arg1,arg2...argN

anonymous-template中不能使用it，通过arg来获取对应的值

&lt;*attribute*:*t1*(),*t2*(),...,*tN*()&gt;

想当于

```
for (int index = 0; index < attribute.length; index++) {
     int templateIndex = (index+1)%N == 0 ? N, (index+1)%N;
     attribute[index].t[templateIndex]();
}
```

&lt;first(attr)&gt;

如果attr为集合，返回它的第一个元素，否则返回它本身

&lt;last(attr)&gt;

如果attr为集合，返回它的最后一个元素，否则返回它本身

&lt;rest(attr)&gt;

如果attr为集合，返回index&gt;=1的所有子元素，否则返回""

&lt;trunc(attr)&gt;

如果attr为集合，返回index&lt;length(attr)-1的所有子元素，否则返回""

&lt;strip(attr)&gt;

如果attr为集合，返回除null之外元素的集合，否则返回attri本身

&lt;length(attr)&gt;

如果attr为集合，返回集合元素数量，否则返回1

`<\uXXXX>`Unicode字符 

 

五，条件语句

 

语法  **注释**  &lt;if(*attribute*)&gt;*subtemplate*  
&lt;else&gt;*subtemplate2*  
&lt;endif&gt;

关于条件的真假判定：

1.attribute存在

2.attribute!=null

3.!(attribute instanceof Boolean) || attribute

仅当上述3条件均为true时，条件判定才为true

&lt;if(*x*)&gt;*subtemplate*  
&lt;elseif(*y*)&gt;*subtemplate2*  
&lt;elseif(*z*)&gt;*subtemplate3*  
&lt;else&gt;*subtemplate4*  
&lt;endif&gt;   &lt;if(!*attribute*)&gt;*subtemplate*&lt;endif&gt;  

五，测试代码

    Student.java

```
package com.siyuan.st.entity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Student {
	
	private String name;
	
	private String $optional;
	
	private List<String> classes = new ArrayList<String>();
	
	private Map<String, String> teachers = new HashMap<String, String>();
	
	/**
	 * @return the teachers
	 */
	public Map<String, String> getTeachers() {
		return teachers;
	}

	/**
	 * @param teachers the teachers to set
	 */
	public void setTeachers(Map<String, String> teachers) {
		this.teachers = teachers;
	}

	/**
	 * @return the $optional
	 */
	public String get$optional() {
		return $optional;
	}

	/**
	 * @param $optional the $optional to set
	 */
	public void set$optional(String $optional) {
		this.$optional = $optional;
	}

	/**
	 * @return the classes
	 */
	public List<String> getClasses() {
		return classes;
	}

	/**
	 * @param classes the classes to set
	 */
	public void setClasses(List<String> classes) {
		this.classes = classes;
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}
	
}
```

   STTest.java

```
package com.siyuan.st.test;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.antlr.stringtemplate.StringTemplate;
import org.antlr.stringtemplate.StringTemplateGroup;

import com.siyuan.st.entity.Student;

public class STTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		String simple = "SimpleST $attribute;separator=\" \"$ \n" +
				"$first(attribute);separator=\" \"$ \n" +
				"$last(attribute);separator=\" \"$ \n" +
				"$rest(attribute);separator=\" \"$ \n" +
				"$trunc(attribute);separator=\" \"$ \n" +
				"$strip(attribute);separator=\" \"$ \n" +
				"$length(attribute)$ \n" +
				"$attr.name$=$attr.value$ \n" +
				"$[attribute, attr];separator=\" \"$ \n" +
				"$\\u2021$";
		//new SimpltTemplate 对象
		StringTemplate simpleST = new StringTemplate(simple);
		//attribute设置
		simpleST.setAttribute("attribute", null);
		//注意：不同于MAP，对同一个attribute多次赋值时，不会覆盖，而是将新旧值合并成一个数组,并且会忽略null值
		simpleST.setAttribute("attribute", "attr1");
		simpleST.setAttribute("attribute", "attr2");
		//可以比较两种方式的区别
//		simpleST.setAttribute("attribute", Arrays.asList(new String[]{null, "attr1", "attr2"}));
		Map<String, String> attr = new HashMap<String, String>();
		//可以通过map.key的方式获取map中的值
		attr.put("name", "attr");
		attr.put("value", "val");
		simpleST.setAttribute("attr", attr);
		//输出
		System.out.println(simpleST);
		
		//综合应用
		System.out.println("\n---------------------------------------\n");
		String template = "Student[name=$stu.name$ \n" +
				"\t \\$optional=$stu.(\"\\$optional\")$ \n" +
				"\t classes=$stu.classes;null=\"XXX\",separator=\" \"$ \n" +
				"\t teachers=$stu.teachers;null=\"...\",separator=\",\"$ ]";
		StringTemplate st = new StringTemplate(template);
		Student stu = new Student();
		stu.setName("student1");
		stu.set$optional("false");
		stu.setClasses(Arrays.asList(new String[]{"Math", "English", null}));
//		注意Map的迭代结果只输出value
		Map<String, String> teachers = new HashMap<String, String>();
		teachers.put("Math", "Mr. M");
		teachers.put("English", "Miss E");
		teachers.put(null, null);
		stu.setTeachers(teachers);
		st.setAttribute("stu", stu);
		System.out.println(st);
		
		//模板调用 必须在同一个StringTemplateGroup中的StringTemplate才能相互调用
		System.out.println("\n---------------------------------------\n");
		//new StringTemplateGroup 对象
		StringTemplateGroup stGroup = new StringTemplateGroup("test");
		//在stGroup中定义一个名字为method的StringTemplate
		stGroup.defineTemplate("method", "\n method invoke $attr$");
		stGroup.defineTemplate("main", "main $method(attr=attribute)$");
		stGroup.defineTemplate("element", "\n $i$ $i0$ $it$");
//		stGroup.defineTemplate("iterator", "Iterator $list:element()$ \n $list:{it1| \n $it1$ }$");
//		stGroup.defineTemplate("iterator", "Iterator $list:element():method()$");
//		stGroup.defineTemplate("iterator", "Iterator $list:element(),method()$");
		stGroup.defineTemplate("iterator", "Iterator $list,list1:{arg1,arg2| \n $arg1$ $arg2$}$");
		//获得stGroup中名为main的StringTemplate
		StringTemplate main = stGroup.getInstanceOf("main");
		main.setAttribute("attribute", "attri");
		System.out.println(main);
		StringTemplate iterator = stGroup.getInstanceOf("iterator");
		iterator.setAttribute("list", Arrays.asList(new String[]{null, "a", "b", "c", "d"}));
		iterator.setAttribute("list1", Arrays.asList(new String[]{"a1", "b1", "c1"}));
		System.out.println(iterator);
	}

}
```

六,参考资料

[http://www.antlr.org/wiki/display/ST/StringTemplate+cheat+sheet](http://www.antlr.org/wiki/display/ST/StringTemplate+cheat+sheet)