Any insights? New listing built-ins in 2.3.23

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view

Any insights? New listing built-ins in 2.3.23

Daniel Dekany
Prior to 2.3.23, you could only access the listing state with the
<loopVarName>_index <loopVarName>_has_next variables.

  <#list xs as x>
    ${x_index}: ${x}<#if x_has_next>, </#if>

This old approach has some problems:

- It's not possible to add new listing state variables without
  breaking backward compatibility.

- It's not obvious for the user where those variable are coming from,
  and that they could be looked up in the Manual (and then where).

I have re-used the built-in mechanism (exp?some_builtin) to address
these. As you might know, built-ins are put into categories according
the supported left hand value type (string, number, etc.). I have
added a new category, loop variable built-ins. These don't work with
the value of the left hand expression, instead they require a loop
variable on the left side, which Freemarker uses to identify the
ongoing looping:

  <#list xs as x>
    ${x?index}: ${x}<#if x?has_next>, </#if>

Now the user can just look these up in the built-in reference. Also
the parser(!) can do more checks (y?index is wrong because y is not a
loop variable, and x?idnex is wrong because there's no "idnex"
built-in, while y_index or x_idnex would pass and then die on

But the real point is that now I could add some convenience built-ins
that address typical listing tasks in templates (FTL meant to be
highly specialized language, and people do a lot of listings with some
typical patterns):

- x?counter: means x?index + 1, and that's what you print for numbered
- ?is_odd_item and ?is_even_item: means x?index % 2 == 0 or the
  inverse of that.
- ?item_parity: returns "even" or "odd", meant to be used like
  <td class="${x?item_parity}Row">
- ?item_parity_cap: returns "Even" or "Odd"
- ?item_cycle: generalized ?item_parity, used like
  x?item_cycle("color1", "color2", "color3")
- x?is_first, x?is_last

One my wonders why's "item" in some names, and not in others. It's
because ?index, ?is_first, etc. can't be misinterpreted, while for
example ?is_odd without the ..._item could be misinterpreted as asking
if the number on the left side is odd. (I have also though about
x?index?is_odd, but that's already a bug there (if you spot why). So
that's why I don't liked it. Also because I think it required more
thinking on the side of the template author, for such a basic
templating task.)

This all can be tried in trunk BTW.

Best regards,
 Daniel Dekany

FreeMarker-devel mailing list
[hidden email]