1. 程式人生 > >velocity自定義標籤和指令

velocity自定義標籤和指令

velocity本身支援自定義標籤和指令的擴充套件,

在 Velocity 模板語言的語法中,以美元符 $ 開頭的為變數的宣告或者引用,而以井號 # 開頭的語句則為 Velocity 的指令(Directive)。

velocity支援的指令有:#set,#foreach,#if #else #end,#parse,#include,#evaluate,#define,#macro,

在velocity的jar包中的directive.properties中定義了這些實現:

[html] view plaincopyprint?
  1. directive.1=org.apache.velocity.runtime.directive.Foreach  
  2. directive.2=org.apache.velocity.runtime.directive.Include  
  3. directive.3=org.apache.velocity.runtime.directive.Parse  
  4. directive.4=org.apache.velocity.runtime.directive.Macro  
  5. directive.5=org.apache.velocity.runtime.directive.Literal  
  6. directive.6=org.apache.velocity.runtime.directive.Evaluate  
  7. directive.7
    =org.apache.velocity.runtime.directive.Break  
  8. directive.8=org.apache.velocity.runtime.directive.Define  
directive.1=org.apache.velocity.runtime.directive.Foreach
directive.2=org.apache.velocity.runtime.directive.Include
directive.3=org.apache.velocity.runtime.directive.Parse
directive.4=org.apache.velocity.runtime.directive.Macro
directive.5=org.apache.velocity.runtime.directive.Literal
directive.6=org.apache.velocity.runtime.directive.Evaluate
directive.7=org.apache.velocity.runtime.directive.Break
directive.8=org.apache.velocity.runtime.directive.Define

自定義標籤和指定,比如我們定義了下面的remoteVelocity指令
[html] view plaincopyprint?
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4. <meta http-equiv="Content-Type" content="text/html; charset=gbk" />  
  5. <title>click ok page</title>  
  6. </head>  
  7. <body>  
  8.   This app runs well  
  9.   #set($monkey= {"banana" : "good", "roast beef" : "bad"})  
  10.   #remoteVelocity("namespace","velocityname",$monkey)  
  11. </body>  
  12. </html>  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<title>click ok page</title>
</head>
<body>
  This app runs well
  
  #set($monkey= {"banana" : "good", "roast beef" : "bad"})

  #remoteVelocity("namespace","velocityname",$monkey)
</body>
</html>

要對這個指令的實現要繼承Directive這個類,這個巨集我們可以從其他服務獲取vm的內容,動態渲染,這種方式可以統一管理公共模板,
[java] view plaincopyprint?
  1. import java.io.IOException;  
  2. import java.io.Serializable;  
  3. import java.io.StringWriter;  
  4. import java.io.Writer;  
  5. import java.util.HashMap;  
  6. import java.util.Map;  
  7. import org.apache.velocity.VelocityContext;  
  8. import org.apache.velocity.app.VelocityEngine;  
  9. import org.apache.velocity.context.InternalContextAdapter;  
  10. import org.apache.velocity.exception.MethodInvocationException;  
  11. import org.apache.velocity.exception.ParseErrorException;  
  12. import org.apache.velocity.exception.ResourceNotFoundException;  
  13. import org.apache.velocity.runtime.directive.Directive;  
  14. import org.apache.velocity.runtime.parser.node.Node;  
  15. import org.apache.velocity.runtime.parser.node.SimpleNode;  
  16. import org.springframework.beans.factory.annotation.Autowired;  
  17. import com.alibaba.citrus.service.template.TemplateService;  
  18. import com.alibaba.click.util.HostUtil;  
  19. public class RemoteVelocity extends Directive{  
  20.     @Autowired  
  21.     TemplateService templateService;  
  22.     private static final VelocityEngine velocityEngine = new VelocityEngine();  
  23.     @Override  
  24.     public String getName() {  
  25.         return "remoteVelocity";  
  26.     }  
  27.     @Override  
  28.     public int getType() {  
  29.         return LINE;  
  30.     }  
  31.     @Override  
  32.     public boolean render(InternalContextAdapter context, Writer writer,  
  33.             Node node) throws IOException, ResourceNotFoundException,  
  34.             ParseErrorException, MethodInvocationException {  
  35.         SimpleNode sn_region = (SimpleNode) node.jjtGetChild(0);     
  36.         String region = (String)sn_region.value(context);     
  37.         SimpleNode sn_key = (SimpleNode) node.jjtGetChild(1);     
  38.         Serializable key = (Serializable)sn_key.value(context);     
  39.         SimpleNode sn_data = (SimpleNode) node.jjtGetChild(2);   
  40.         Object data = sn_data.value(context);     
  41.         Map map = new HashMap();  
  42.         map.put("data", data);  
  43. //      String vel = HostUtil.getResponseText("http://127.0.0.1/index.html");   
  44.         String vel="#foreach($member in $data.entrySet())<li>$member.key - $member.value</li>#end ";  
  45.         writer.write(renderTemplate(map,vel));  
  46.         return true;  
  47.     }  
  48.     public static String renderTemplate(Map params,String vimStr){  
  49.         VelocityContext context = new VelocityContext(params);  
  50.         StringWriter writer = new StringWriter();  
  51.         try {  
  52.             velocityEngine.evaluate(context, writer, "", vimStr);  
  53.         } catch (ParseErrorException e) {  
  54.             // TODO Auto-generated catch block   
  55.             e.printStackTrace();  
  56.         } catch (MethodInvocationException e) {  
  57.             // TODO Auto-generated catch block   
  58.             e.printStackTrace();  
  59.         } catch (ResourceNotFoundException e) {  
  60.             // TODO Auto-generated catch block   
  61.             e.printStackTrace();  
  62.         } catch (IOException e) {  
  63.             // TODO Auto-generated catch block   
  64.             e.printStackTrace();  
  65.         }//渲染模板   
  66.         return writer.toString();  
  67.     }  
  68. }  
import java.io.IOException;
import java.io.Serializable;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.directive.Directive;
import org.apache.velocity.runtime.parser.node.Node;
import org.apache.velocity.runtime.parser.node.SimpleNode;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.citrus.service.template.TemplateService;
import com.alibaba.click.util.HostUtil;

public class RemoteVelocity extends Directive{
	
	@Autowired
	TemplateService templateService;
	
	private static final VelocityEngine velocityEngine = new VelocityEngine();

	@Override
	public String getName() {
		return "remoteVelocity";
	}

	@Override
	public int getType() {
		return LINE;
	}

	@Override
	public boolean render(InternalContextAdapter context, Writer writer,
			Node node) throws IOException, ResourceNotFoundException,
			ParseErrorException, MethodInvocationException {
		SimpleNode sn_region = (SimpleNode) node.jjtGetChild(0);   
        String region = (String)sn_region.value(context);   
        SimpleNode sn_key = (SimpleNode) node.jjtGetChild(1);   
        Serializable key = (Serializable)sn_key.value(context);   

		SimpleNode sn_data = (SimpleNode) node.jjtGetChild(2); 
		Object data = sn_data.value(context);   
		Map map = new HashMap();
		map.put("data", data);
//		String vel = HostUtil.getResponseText("http://127.0.0.1/index.html");
		String vel="#foreach($member in $data.entrySet())<li>$member.key - $member.value</li>#end ";
		writer.write(renderTemplate(map,vel));
        return true;
	}
	
	public static String renderTemplate(Map params,String vimStr){
        VelocityContext context = new VelocityContext(params);
        StringWriter writer = new StringWriter();
        try {
			velocityEngine.evaluate(context, writer, "", vimStr);
		} catch (ParseErrorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MethodInvocationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ResourceNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}//渲染模板
        return writer.toString();
	}

}

node.jjtGetChild(2) 這個方法可以獲取對應指令的引數,下標從0開始,

在web工程的WEB-INF下面定義velocity.properties這個配置檔案,使用者擴充套件的指令最好放到這個檔案裡面,velocity的jar包裡面提供了預設實現,我們可以覆蓋重新定義自己的擴充套件,類就是對應自己的擴充套件類的類名

 #自定義標籤


[html] view plaincopyprint?
  1. userdirective=com.alibaba.click.test.RemoteVelocity  
userdirective=com.alibaba.click.test.RemoteVelocity

這樣啟動後就可以正常使用了。

Directive的三個方法:

[html] view plaincopyprint?
  1. getName:指令的名稱  
  2. getType:當前有LINE,BLOCK兩個值,line行指令,不要end結束符,block塊指令,需要end結束符  
  3. public boolean render(InternalContextAdapter context, Writer writer,  
  4.             Node node) 具體處理過程  
getName:指令的名稱
getType:當前有LINE,BLOCK兩個值,line行指令,不要end結束符,block塊指令,需要end結束符
public boolean render(InternalContextAdapter context, Writer writer,
			Node node) 具體處理過程