public class Size { private int width; private int height; public Size(int width, int height) { this.width = width; this.height = height; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } }
public class Attr { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
Controoler代码片断:
List datalist = new ArrayList<>(); datalist.add(new Size(50, 50)); datalist.add(new Size(500, 500)); Attr attr = new Attr(); attr.setName("width"); set("datalist", datalist); set("attr", attr);
html页面:
#(attr.name) //输出值:width #for(data : datalist) #(data.attr.name) //本意是想得到 data.width的值,但不能直接写 #(data.width),请问这里应该怎么办才好? #end
尝试了以下三种方法都不得行:
#(data[attr.name]) //报错:Only the list array and map is supported by index access
#(data.attr.name) //报错:public field not found: "data.attr" and public getter method not found: "data.getAttr()"
#(data.get(attr.name)) //报错:public method not found: com.jfinal.admin.common.Size.get(java.lang.String)
============感谢大神提供改造思路,修改以下代码正常========================
public class Size<M extends Size<M>> extends Model<M>{ public Size(int width, int height) { this.setWidth(width); this.setHeight(height); } public int getWidth() { return getInt("width"); } public void setWidth(int width) { set("width", width); } public int getHeight() { return getInt("height"); } public void setHeight(int height) { set("height", height); } }
html页面:
#for(data : datalist) #(data.get(attr.name)) #end
可以正常动态获取属性值了。
项目:JFinal
一个是声明式:
#if('width' == attr.name)#(data.width)
#elseif('height' == attr.name)#(data.height)
#end
还有改变Size 类,使其继承Kv对象,然后去掉成员属性,this.赋值和取值改使用set 和get 方法代替。
这样模板中就可以这样动态取了:
#(data.get(attr.name))
还有其他方式,比如增加SharedMethod方法里面转调反射方法取值,
#(get(data, attr.name))
还可扩展一下Engine等