freemarker if statement sequencing

1k views Asked by At

I'm trying to write an #if statement with a sequence of numbers. Basically, if a certain field matches any of a subset of numbers (shown below with || or operators) then assign it as "bayarea", elseif a different subset, then a different name, etc. Is this possible without a bunch of nested "or" statements?

I'm getting a syntax error saying that it's expecting a boolean yes/no statement.

<#if TEST_CONTACTS_LIST.PREFERRED_STORE == 
{12||21||22||38||46||67||71||74||76||77||83||86||104||113||119||143>
{bayarea}
 <#elseif TEST_CONTACTS_LIST.PREFERRED_STORE == 
{34||62||84||91||137||144||152||169}>
{blueridge}
<#elseif TEST_CONTACTS_LIST.PREFERRED_STORE == 
{18||44||49||50||61||68||121||182}>
 {frontrange}
<#else>
</#if>
2

There are 2 answers

0
ddekany On

You don't need nesting:

<#if TEST_CONTACTS_LIST.PREFERRED_STORE == 12
     || TEST_CONTACTS_LIST.PREFERRED_STORE == 21 || ...>

Though that's surely too verbose, but you can do this:

<#assign store = TEST_CONTACTS_LIST.PREFERRED_STORE>
<#if store == 12 || store == 21 || ...>

But I think what you are looking for is this (or this combined with the #assign, if you have several #elseif-s):

<#if [12, 21, ...]?seq_contains(TEST_CONTACTS_LIST.PREFERRED_STORE)>

This is a possibility too (just don't forget the #break-s):

<#switch TEST_CONTACTS_LIST.PREFERRED_STORE>
   <#case 12><#case 21>...
     {bayarea}
     <#break>
   <#case 34><#case 62>...
     {bluebridge}
     <#break>
   ...
</#switch>
0
user10095352 On

Those are four good answers above. To expand on it, I'd do something like this:

<#assign pref_store = TEST_CONTACTS_LIST.PREFERRED_STORE>

<#assign area = "">

<#assign group1 = [12,21,22,38,46,67,71,74,76,77,83,86,104,113,119,143]>

<#assign group2 = [34,62,84,91,137,144,152,169]>

<#assign group3 = [18,44,49,50,61,68,121,182]>

<#if group1?seq_contains(pref_store)>

    <#assign area = "bayarea">

<#elseif group2?seq_contains(pref_store)>

    <#assign area = "blueridge">

<#elseif group3?seq_contains(pref_store)>

    <#assign area = "frontrange">

<#else>

    <#assign area = "whatever">

</#if>

Your Preferred Store Area is ${area}.


Alternatively, instead of Sequences / Arrays, you could also set these values as a string.

For example:

<#assign pref_store = "${TEST_CONTACTS_LIST.PREFERRED_STORE}">

<#assign group1 = "12,21,22,38,46,67,71,74,76,77,83,86,104,113,119,143">

then the if statement would be the following:

<#if group1?contains(pref_store)>   

(Notice the ?contains instead of ?seq_contains)

etc..