Java 无法使用for标记在Pebble模板引擎中遍历数组列表
我一直试图用Java 无法使用for标记在Pebble模板引擎中遍历数组列表,java,template-engine,pebble,Java,Template Engine,Pebble,我一直试图用{%for item in items%}语法遍历一个项目数组列表,但没有用。 不停地扔 java.lang.UnsupportedOperationException at java.util.AbstractMap.put(AbstractMap.java:209) at com.mitchellbosecke.pebble.template.Scope.put(Scope.java:53) at com.mitchellbosecke.pebble.
{%for item in items%}
语法遍历一个项目数组列表,但没有用。
不停地扔
java.lang.UnsupportedOperationException
at java.util.AbstractMap.put(AbstractMap.java:209)
at com.mitchellbosecke.pebble.template.Scope.put(Scope.java:53)
at com.mitchellbosecke.pebble.template.ScopeChain.put(ScopeChain.java:61)
at com.mitchellbosecke.pebble.template.EvaluationContext.put(EvaluationContext.java:162) exception.
尝试使用基本数组、映射和许多类型的列表实现,结果总是这样。在执行iterable测试时,数组列表返回true,因此我认为使用for标记应该是iterable。我做错什么了吗?请在下面查找代码
PebbleTemplate template = pebbleEngine.getTemplate(
"{% if menuItems is iterable %}{% for menuItem in menuItems %}" +
" \"{{ menuItem }}\" this" +
"{% endfor %}{% else %}nope{% endif %}");
StringWriter writer = new StringWriter();
List<String> menuItems = new ArrayList<>();
menuItems.add("menu item1");
menuItems.add("menu item2");
menuItems.add("menu item 3");
template.evaluate(writer, Collections.<String,Object>singletonMap("menuItems", menuItems));
System.out.println(writer);
PebbleTemplate=pebbleEngine.getTemplate(
“{%如果menuItems是iterable%}{%对于menuItems%}中的menuItem”+
“\{{menuItem}}\\\此”+
“{%endfor%}{%else%}nope{%endif%}”);
StringWriter编写器=新的StringWriter();
List menuItems=new ArrayList();
菜单项。添加(“菜单项1”);
菜单项添加(“菜单项2”);
菜单项。添加(“菜单项3”);
评估(writer,Collections.singletonMap(“menuItems”,menuItems));
System.out.println(writer);
这取决于单例映射的使用。
改用哈希映射
,应该可以工作
解释。范围的初始化如下所示:
public Scope(Map<String, Object> backingMap, boolean isLocal) {
this.backingMap = (Map)(backingMap == null?new HashMap():backingMap);
this.isLocal = isLocal;
}
public作用域(映射backingMap,布尔isLocal){
this.backingMap=(Map)(backingMap==null?新HashMap():backingMap);
this.isLocal=isLocal;
}
因此,它实际上重用了您提供的地图。当它在映射上调用put
时,会抛出一个异常,因为它是一个单例。这很奇怪。从来没有想到我提供的用于模板评估的映射会被for循环机制更新。不管怎么说,它都很有魅力。这是我在for循环之后在地图上看到的。{loop={length=3,index=2},menuItems=[菜单项1,菜单项2,菜单项3],menuItem=菜单项3}@javabot我同意!我一点也不喜欢这种方法。这还不够防御性!为了证明这一点,我使用了Spring,并且模型是一个映射,它可能不能被认为是不变的。事实上,通过单个控制器调用,它可以传递给用@RequestMapping
注释的方法,也可以传递给用@modeldattribute
注释的几个方法。如果它是不可变的,则不能动态填充。