默认情况下,beetl的html标签并不支持父子嵌套,就像类似jsp标签那样,父标签需要知道子标签的信息,子标签也需要知道父标签信息。但是beetl只需要简单扩展,就能完成嵌套标签支持。
首先看一个最终的使用效果,实现俩个html标签table.tag,tr.tag.可以在页面上这么用:
名称
在阅读table.tag,tr.tag之前,先看看如何扩展html标签
首先,需要扩展 htmltagsupportwrapper,这个类是html标签实现类,我们可以扩展此类来定制化需求,然后重新注册覆盖。因此实现类
public class htmlnesttagsupportwrapper extends htmltagsupportwrapper{public void render(){....}}
然后在配置文件配置tag.htmltag= bingo.util.htmlnesttagsupportwrapper 就可以生效。
htmlnesttagsupportwrapper用到了tagnestcontext类,这个类其实就是一个树形结构,记录了parent的context,记录了当前tag信息,以及记录了子tag的context,这样,每个tag都可以访问父tag或者子tag:代码如下
public class tagnestcontext {private tag tag = null;private tagnestcontext parent = null;private list children = null;public tag gettag() { return tag;}public void settag(tag para) { this.tag = para;}public tagnestcontext getparent() { return parent;}public void setparent(tagnestcontext parent) { this.parent = parent;}public list getchildren() { if(children==null) children = new arraylist(); return children;}public void setchildren(list children) { this.children = children;}}
回头在看看 htmlnesttagsupportwrapper实现
public void render(){ httpservletrequest request = (httpservletrequest)this.ctx.getglobal(request); tagnestcontext tnc = (tagnestcontext)request.getattribute(tagcontext); if(tnc==null){ tnc = new tagnestcontext(); tnc.settag(this); request.setattribute(tagcontext, tnc); super.render(); request.removeattribute(tagcontext); }else{ tagnestcontext child = new tagnestcontext(); child.setparent(tnc); child.settag(this); tnc.getchildren().add(child); request.setattribute(tagcontext, child); super.render(); //重新设置 request.setattribute(tagcontext, child.getparent()); }}public string gettagname(){ return (string)this.args[0];}public object get(string attr){ map map = (map)this.args[1]; return map.get(attr);}
如上代码所示,但渲染某个htmltag前(调用super.render()前),可以从request里获取nestcontext,如果没有,生成一个新的nestcontext。如果已经存在。则将当前nestcontext加入到父nestcontext。渲染完毕后,需要重置nestcontext。
最后看一下tr.tag如何实现,tr仅仅实现了生成表头
${tagbody}
table.tag 则要麻烦点,需要知道有多少个tr,然后输出数据,内容如下:
${tagbody}
ettagcontext 是一个注册方法,获取当前context.可以自行开发一个