Stringtemplate compare strings does not work

蹲街弑〆低调 提交于 2019-12-04 03:25:57

问题


Can someone explain why this does not work ?

StringTemplate query = new StringTemplate("hello " +  
                "$if(param==\"val1\")$" +  
                " it works! " +  
                "$endif$ " +  
                "world");  
        query.setAttribute("param", "val1");  
        System.out.println("result: "+query.toString());  

It throws

eval tree parse error :0:0: unexpected end of subtree at org.antlr.stringtemplate.language.ActionEvaluator.ifCondition(ActionEvaluator.java:815) at org.antlr.stringtemplate.language.ConditionalExpr.write(ConditionalExpr.java:99)


回答1:


ST doesn't allow computation in the templates. That would make it part of the model.




回答2:


You can't compare strings inside stringtemplate, unfortunately, but you can send a result of such a comparison into template as a parameter:

StringTemplate query = new StringTemplate("hello " +  
                "$if(paramEquals)$" +  
                " it works! " +  
                "$endif$ " +  
                "world");  
        query.setAttribute("paramEquals", param.equals("val1"));  
        System.out.println("result: "+query.toString());

It might not be what you're looking for, since every time you need to add a comparison you have to pass an extra parameter, and for loops it's even worse. But this is one workaround that may work for simple cases.



来源:https://stackoverflow.com/questions/4195828/stringtemplate-compare-strings-does-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!