velocity自定義標籤和指令
阿新 • • 發佈:2018-12-25
velocity本身支援自定義標籤和指令的擴充套件,
在 Velocity 模板語言的語法中,以美元符 $ 開頭的為變數的宣告或者引用,而以井號 # 開頭的語句則為 Velocity 的指令(Directive)。
velocity支援的指令有:#set,#foreach,#if #else #end,#parse,#include,#evaluate,#define,#macro,
在velocity的jar包中的directive.properties中定義了這些實現:
[html] view plaincopyprint?- 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
- 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?
- <!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>
<!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?
- 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();
- }
- }
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?
- userdirective=com.alibaba.click.test.RemoteVelocity
userdirective=com.alibaba.click.test.RemoteVelocity
這樣啟動後就可以正常使用了。
Directive的三個方法:
[html] view plaincopyprint?- getName:指令的名稱
- getType:當前有LINE,BLOCK兩個值,line行指令,不要end結束符,block塊指令,需要end結束符
- public boolean render(InternalContextAdapter context, Writer writer,
- Node node) 具體處理過程
getName:指令的名稱
getType:當前有LINE,BLOCK兩個值,line行指令,不要end結束符,block塊指令,需要end結束符
public boolean render(InternalContextAdapter context, Writer writer,
Node node) 具體處理過程