2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > Why I can't use non-string key in the myMap[myKey] expression? And what to do now?

Why I can't use non-string key in the myMap[myKey] expression? And what to do now?

时间:2022-11-26 21:30:53

相关推荐

Why I can't use non-string key in the myMap[myKey] expression? And what to do now?

Why I can’t use non-string key in the myMap[myKey] expression? And what to do now?

The "hash" type of the FreeMarker Template Language (FTL) is not the same as Java's Map. FTL's hash is an associative array too, but it uses string keys exclusively. This is because it was introduced for sub variables (as password in user.password, which is the same as user["password"]), and variable names are strings.If you only need to list the key-value pairs of a Map, you can just write something like <#list myMap as k, v>${k}: ${v}</#list> (see more about the list directive here). This enumerates the Map entries, and supports non-string keys. This requires FreeMarker 2.3.25 or later. (If for some reason you can't upgrade to 2.3.25, you can use the Java API of Map instead, like <#list myMap?api.entrySet() as kvp>${kvp.key}: ${kvp.value}</#list>.)If you need to do more than listing, you will have to turn to the Java API of the Map. You can do it like this: myMap?api.get(nonStringKey). However, for ?api to be enabled, you may need to configure FreeMarker a bit (see more here).Note that as Java's Map is particular about the exact class of the key, at least for numerical keys calculated inside the templates you will have to cast them to the proper Java type, otherwise the item will not be found. For example if you use Integer keys in a Map, then you should write ${myMap.get(numKey?int)}. This is because of FTL's deliberately simplified type system has only a single numerical type, while Java distinguishes a lot of numerical types. Note that the casting is not needed when the key value comes directly from the data-model (i.e., you didn't modified its value with arithmetical calculations in the template), including the case when it's the return value of a method, and it was of the proper class before wrapping, because then the result of the unwrapping will be of the original type.

参考/docs/app_faq.html#faq_nonstring_keys

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。