velocity自定义标签和指令

Posted skiwndhw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了velocity自定义标签和指令相关的知识,希望对你有一定的参考价值。

velocity本身支持自定义标签和指令的扩展,

在 Velocity 模板语言的语法中,以美元符 $ 开头的为变量的声明或者引用,而以井号 # 开头的语句则为 Velocity 的指令(Directive)。

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

在velocity的jar包中的directive.properties中定义了这些实现:

 

  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指令

 

 

  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.     
  10.   #set($monkey= {"banana" : "good", "roast beef" : "bad"})  
  11.   
  12.   #remoteVelocity("namespace","velocityname",$monkey)  
  13. </body>  
  14. </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的内容,动态渲染,这种方式可以统一管理公共模板,

 

 

  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.   
  8. import org.apache.velocity.VelocityContext;  
  9. import org.apache.velocity.app.VelocityEngine;  
  10. import org.apache.velocity.context.InternalContextAdapter;  
  11. import org.apache.velocity.exception.MethodInvocationException;  
  12. import org.apache.velocity.exception.ParseErrorException;  
  13. import org.apache.velocity.exception.ResourceNotFoundException;  
  14. import org.apache.velocity.runtime.directive.Directive;  
  15. import org.apache.velocity.runtime.parser.node.Node;  
  16. import org.apache.velocity.runtime.parser.node.SimpleNode;  
  17. import org.springframework.beans.factory.annotation.Autowired;  
  18.   
  19. import com.alibaba.citrus.service.template.TemplateService;  
  20. import com.alibaba.click.util.HostUtil;  
  21.   
  22. public class RemoteVelocity extends Directive{  
  23.       
  24.     @Autowired  
  25.     TemplateService templateService;  
  26.       
  27.     private static final VelocityEngine velocityEngine = new VelocityEngine();  
  28.   
  29.     @Override  
  30.     public String getName() {  
  31.         return "remoteVelocity";  
  32.     }  
  33.   
  34.     @Override  
  35.     public int getType() {  
  36.         return LINE;  
  37.     }  
  38.   
  39.     @Override  
  40.     public boolean render(InternalContextAdapter context, Writer writer,  
  41.             Node node) throws IOException, ResourceNotFoundException,  
  42.             ParseErrorException, MethodInvocationException {  
  43.         SimpleNode sn_region = (SimpleNode) node.jjtGetChild(0);     
  44.         String region = (String)sn_region.value(context);     
  45.         SimpleNode sn_key = (SimpleNode) node.jjtGetChild(1);     
  46.         Serializable key = (Serializable)sn_key.value(context);     
  47.   
  48.         SimpleNode sn_data = (SimpleNode) node.jjtGetChild(2);   
  49.         Object data = sn_data.value(context);     
  50.         Map map = new HashMap();  
  51.         map.put("data", data);  
  52. //      String vel = HostUtil.getResponseText("http://127.0.0.1/index.html");   
  53.         String vel="#foreach($member in $data.entrySet())<li>$member.key - $member.value</li>#end ";  
  54.         writer.write(renderTemplate(map,vel));  
  55.         return true;  
  56.     }  
  57.       
  58.     public static String renderTemplate(Map params,String vimStr){  
  59.         VelocityContext context = new VelocityContext(params);  
  60.         StringWriter writer = new StringWriter();  
  61.         try {  
  62.             velocityEngine.evaluate(context, writer, "", vimStr);  
  63.         } catch (ParseErrorException e) {  
  64.             // TODO Auto-generated catch block   
  65.             e.printStackTrace();  
  66.         } catch (MethodInvocationException e) {  
  67.             // TODO Auto-generated catch block   
  68.             e.printStackTrace();  
  69.         } catch (ResourceNotFoundException e) {  
  70.             // TODO Auto-generated catch block   
  71.             e.printStackTrace();  
  72.         } catch (IOException e) {  
  73.             // TODO Auto-generated catch block   
  74.             e.printStackTrace();  
  75.         }//渲染模板   
  76.         return writer.toString();  
  77.     }  
  78.   
  79. }  
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包里面提供了默认实现,我们可以覆盖重新定义自己的扩展,类就是对应自己的扩展类的类名

 #自定义标签


 

  1. userdirective=com.alibaba.click.test.RemoteVelocity  
userdirective=com.alibaba.click.test.RemoteVelocity

 

这样启动后就可以正常使用了。

Directive的三个方法:

  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) 具体处理过程

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow









以上是关于velocity自定义标签和指令的主要内容,如果未能解决你的问题,请参考以下文章

JSP回顾

Sublime Text3自定义代码片段

Velocity——宏

汇编代码的自定义缩进功能

JSP自定义tag控件标签

为片段制作自定义列表视图?