Free mark中map的遍历
- 一、map遍历
- 1、遍历key
- 2、遍历value
- 二、map的key不是string场景
- 1、场景描述
- 2、解决
- 1)配置
- a、SpringBoot的配置
- b、SpringMVC的配置
- c、自定义配置
- 2)使用
mark中map的遍历)
一、map遍历
1、遍历key
<#list map?keys as key>
<#-- key值 -->
${key}
<#-- 根据key值获取value -->
${map[key]}
</#list>
2、遍历value
<#list map?values as value>
<#-- value值 -->
${value}
</#list>
二、map的key不是string场景
1、场景描述
我在使用freemark模板生成html时,需要模板加载的数据map的key是页面下标,后台根据计算得出,页面中根据下标计算用来动态切换<div块,所以用数值类型可以省去大量的和字符串的转换。
当使用根据key遍历来获取value值时抛出如下异常:
Tip: You had a numberical value inside the []. Currently that's only supported for
sequences (lists) and strings. To get a Map item with a non-string key, use myMap?
(myKey)
大致意思就是map的key只能为string类型。
2、解决
最初我想将key转换成string获取value,后来感觉太愚蠢了,存入的key是整型,根据string类型的key是取不到value的。
后来查找资料说可以修改一个ObjectWrapper配置就可以解决,这个ObjectWrapper就是freemark的对象包装器,关于它的作用可以查阅官网介绍
freemark-对象包装器.
ObjectWrapper是一个接口,freemark提供了3个实现类和一个实现方法来供我们使用
public interface ObjectWrapper {
ObjectWrapper BEANS_WRAPPER = BeansWrapper.getDefaultInstance();
//默认使用
ObjectWrapper DEFAULT_WRAPPER = DefaultObjectWrapper.instance;
ObjectWrapper SIMPLE_WRAPPER = SimpleObjectWrapper.instance;
TemplateModel wrap(Object var1) throws TemplateModelException;
}
我们下面就介绍如何配置使用
1)配置
a、SpringBoot的配置
.object_wrapper=
该配置其实就是配置freemark的
我们直接自动装配使用这个Bean即可
@Resource
private Configuration configuration;
......
configuration.getTemplate(templateFile);
b、SpringMVC的配置
<bean id="configuration" class="">
<property name="settings">
<props>
<prop key="object_wrapper"></prop>
</props>
</property>
</bean>
该配置其实就是配置freemark的
我们直接自动装配使用这个Bean即可
@Resource
private Configuration configuration;
......
configuration.getTemplate(templateFile);
c、自定义配置
当我们不使用Spring容器来管理这个Bean,而是自己创建该对象时
Configuration configuration=new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
//对象包装器
configuration.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
......
configuration.getTemplate(templateFile);
2)使用
map的遍历不能使用之前的写法了,调整为
<#list () as key>
<#-- key值 -->
${key}
<#-- 根据key值获取value -->
${(key)}
</#list>