Freemaker 操作后端hashmap+json array嵌套
这个问题,是因为多层嵌套,导致直接用hashmap[key]获取json array值,不能直接用于list遍历。
解决方案如下:
后端
List<JSONObject> allArticlesInDomains = new ArrayList<>();
int pageNum = 1, pageSize = 10;
for(JSONObject jb:domains){
final String domainId = jb.optString(Keys.OBJECT_ID);
final String domainName = jb.optString("domainTitle");
final List<JSONObject> latestArticles = (List<JSONObject>) articleQueryService.getDomainArticles(domainId, pageNum, pageSize).opt(Article.ARTICLES);
final JSONObject result = new JSONObject().put(domainName,latestArticles);
allArticlesInDomains.add(result);
}
dataModel.put("allArticlesInDomains", allArticlesInDomains);
前端
.ftl内容
<#assign keys=articlesInDomains.keySet()/>
<#list keys as k>
<span>${k}</span>
<ul>
<#assign json = articlesInDomains[k]?eval/>
<#list json as article>
<#include "common/list-item.ftl">
</#list>
<#if json?size == 0>
<li class="ft-center">
<br><br>
${systemEmptyLabel}<br>
${systemEmptyTipLabel}<br>
<img src="${staticServePath}/images/404/5.gif"/>
</li>
</#if>
<li>
<a class="more" href="${servePath}/recent">${moreRecentArticleLabel}</a>
</li>
</ul>
</#list>
例外
如果string中包含Unicode字符,可能出现如下异常:
FreeMarker template error:
Failed to "?eval" string with this error:
---begin-message---
Syntax error in ?eval-ed string in line 1, column 5535:
Lexical error: encountered "u" (117), after "\"\u5b89\u5927\u7b80\u300a\u7ef8\u7f2a\u300b\u6284\u5199\u5728\\".
---end-message---
The failing expression:
==> articlesInDomains[k]?eval [in template "classic/index.ftl" at line 54, column 57]
----
FTL stack trace ("~" means nesting-related):
- Failed at: #assign json = articlesInDomains[k]?eval [in template "classic/index.ftl" at line 54, column 41]
----
Java stack trace (for programmers):