Richard G
Richard G

Reputation: 5683

checking if a map contains a value in Freemarker Template

I'm trying to check if a map contains a value to conditionally execute some freemarker code. This is what I've got so far:

<#if productLayout.layoutWidgetConfiguration[pos.id]??>
    <#assign configId>${productLayout.layoutWidgetConfiguration[pos.id]}</#assign>
<#else>
    <#assign configId></#assign>
</#if>

But I get this error, which basically fails the if condition.

Error executing FreeMarker template freemarker.core.UnexpectedTypeException: For "...[...]" left-hand operand: Expected a sequence or string (or something that's implicitly convertible to string), but this evaluated to an extended_hash (wrapper: f.t.SimpleHash):
==> productLayout.layoutWidgetConfiguration  [in template "admin/pages/catalog/products/partials/productLayoutEditorRefreshZone.ftl" at line 7, column 22]

The failing instruction (print stack trace for 9 more):
==> #if productLayout.layoutWidgetConfigu...  [in template "admin/pages/catalog/products/partials/productLayoutEditorRefreshZone.ftl" at line 7, column 17]
    at freemarker.core.DynamicKeyName.dealWithNumericalKey(DynamicKeyName.java:141) ~[DynamicKeyName.class:2.3.20]

How can I check if a value exists in a map in a freemarker template?


Update Here:

It seems the hash doesn't like a Long key value if I change it to this, the if check works, but the value doesn't get retrieved even when it exists - so I guess the question now is how to retrieve a value from a hash with a java.lang.Long key?

<#assign configId = "">
<#if productLayout.layoutWidgetConfiguration[pos.id?string]?has_content>
    Hello
    <#assign configId = productLayout.layoutWidgetConfiguration[pos.id?string]>
</#if>
<h1>${pos.id}</h1>  

Upvotes: 1

Views: 7804

Answers (1)

ddekany
ddekany

Reputation: 31122

[] only supports string hash (Map, etc.) keys and numerical sequence (List, array, etc.) indexes. For now the solution is not using [] for Map-s with non-String keys. You can use the Java API of the object instead, like myMap?api.get(nonStringKey), etc. Note that ?api has to be allowed in the configuration; see http://freemarker.org/docs/ref_builtins_expert.html#ref_buitin_api_and_has_api for more.

Upvotes: 1

Related Questions