Search code examples
dust.js

Is it possible to limit a loop in dust.js without using extensions / custom helpers?


I'm using dust.js templates under the LinkedIn fork and Python 'Ashes' implementation.

In a given situation, I have 15 elements in an array. I want to only loop through the first 5 elements.

Does anyone know of a way to structure a template in dust to achieve this without writing helpers -- I'd like to keep the templates working similarly on JS and Python.


Solution

  • You have a few tools available to you, but your options for maintaining cross-compat between Dust and Ashes are going to force compromises.

    Ashes has some of the basic logic helpers found in dust-helpers available, like {@eq} and {@lt}, so I'll assume that you can import that library for Dust as well.

    In Dust, the easiest way to do this would be:

    {#items}
      {@lt key=$idx value=5}{! output the item info !}{/lt}
    {/items}
    

    Dust will iterate over the whole list, but will only output items with an index less than 5.

    Ashes, as you've seen from your opened issue, doesn't support $idx, but only the helper form {@idx/}-- and you can't use helpers as comparators inside another helper like {@lt}.

    So your options are limited. If you can, the best option would be to add an index property to the objects in your array. Hopefully this is as simple as something like:

    return items.map((item, idx) => { item.idx = idx; return item });
    

    Then you could write the same template as above, but use the key on your item:

    {#items}
      {@lt key=idx value=5}{! item info woooo !}{/lt}
    {/items}
    

    If you have no API access, the next-best option is probably using partial contexts, which are supported by Ashes.

    {> itemTemplate:item[0] /}
    {> itemTemplate:item[1] /}
    {> itemTemplate:item[2] /}
    {> itemTemplate:item[3] /}
    {> itemTemplate:item[4] /}
    

    In this example, the context of the partial will be set to one item at a time. Much more succinct than pasting the contents of your loop five times.