List Comprehensions

Effective today, Sailthru now supports Python-style list comprehensions in our Zephyr syntax.

What’s a list comprehension? Basically, it’s an elegant way to run through a list, filtering out items that don’t match a criteria, and possibly applying a transformation to each item in the list.

Why’d we add it, besides the fact that list comprehensions are cool? Mostly because it’s been a bit awkward in the past to filter content. For example, if you have a data feed and want to create a list of the items tagged “fashion”, you had to do a loop like this:

{foreach content as c}

{if contains(c.tags, 'fashion')}

{push('fashion_items', c)}

{/if}

{/foreach}

That’s not exactly a pleasant block of code. List comprehensions provide a way to make it easier. It’s basically the same syntax as Python (and Javascript 1.8):

{fashion_items = [c for c in content if contains(c.tags, 'fashion')]}

If you’re not familiar with list comprehensions, that can be a bit hard to read at first. Read that as:

“let fashion_items be a list constructed from content containing all items tagged “fashion””

What’s up with that odd-looking c for c? The first is the map expression and the second is the variable name. The map expression is useful if you want to transform each item of the list.

So if you wanted to just get the titles of each of the fashion-tagged items, you could do it this way:

{fashion_item_titles = [c.title for c in content if contains(c.tags, 'fashion')]}

And the if section is optional. If you wanted to get the titles of all of the items in your feed, you could do this:

{all_titles = [c.title for c in content)]}

Hope this helps you build even more dynamic templates than before. Feel free to email us anytime if you have questions about this new syntax, and take a look at our documentation for more.