stringtemplatestringtemplate-4

Filter out empty strings in ST4


Consider the following example:

<["foo", "", "bar"]; separator=",">

This gives the result:

foo,,bar

But I need:

foo,bar

Is there any way to filter out empty string values before formating with separator in ST4?

(In real code the values come from another template, which has <if> condition and returns empty result for undesired data from model, and I don't whant to move the condition out of that template to keep templates incapsulated/isolated.)


Solution

  • I've found the workaround with two auxilary things. But it is so creepy...

    DropEmpty ::= ["": [], default: key]
    
    Separated(l, s, w=false) ::= "<if (DropEmpty.(first(l)))><if (w)><s><endif><first(l)><Separated(rest(l), s, true)><else><if (rest(l))><Separated(rest(l), s, w)><endif><endif>"
    
    MyTemplate() ::= <<
    <Separated(["", "foo", "", "bar", "", "", "goo", "", ""], ",")>
    >>
    

    This gives:

    foo,bar,goo