Skip to content

Introduces a new loop variable '$', which can be used inside of sections. #205

wants to merge 1 commit into from

6 participants


The $ variable provides some limited logic inside of sections:
$.first, true if first iteration
$.last, true if last iteration
$.index, 0-based index
$.count, 1-based index

This provides some helpful logic, such as creating lists where you don't want a delimiter before the first item.
The commit includes some tests under 'enhanced_loop'.


I love this idea! I'm going to integrate it into our in-house Mustache implementation. Kudos!

@thegrandpoobah thegrandpoobah added a commit to thegrandpoobah/mustache.js that referenced this pull request May 18, 2012
@thegrandpoobah thegrandpoobah Add enhanced loop feature from @UnquietCode's pull request #205 in up…
thelucid commented Aug 3, 2012

+1 ...also, $.odd and $.even would be good.

@groue groue referenced this pull request in mustache/spec Jan 9, 2013

Mustache shouldn't alter whitespace inside partials #2


+1 for $.odd and $.even


Lacks tests asserting this works. It probably creates variable collision with other objects. Closing due to inactivity.


Definitely creates variable collisions :)

IMO things like this should be handled by the (proposed) filters spec, rather than by blessing names. Add a loop helper that injects whatever magic you want, and do something like:

{{# items | loop }}
  {{# odd }}This is odd!{{/ odd }}
  {{# even }}This is even!{{/ even }}
  {{# first }}This is the first element{{/ first }}
  {{# last }}This is the last element{{/ last }}
  This element's value is {{ value }}.
{{/ items }}

If it's a common enough need, such a helper could even ship with a Mustache implementation.


@bobthecow, what if, in the loop, an item is both even and last? Both sections should be rendered?


I mean, that's up to the template author to decide, right? :)


Sorry, I haven't really looked into filters yet. :)


They just let you define a transform on a value. In this case, we're using it to add loop iteration variables, but you can use it to do anything, really. See this example, for example, which lets you iterate over a hash: bobthecow/mustache.php@3f492a1

It turns out they can be used for other awesome things, too. This issue has examples of using them to block context stack lookup, and as pure-boolean sections.

{{# nestedThing | only }}
  {{ truthyThing }} doesn't work in here, because we're limited to only properties of nestedThing :)
{{/ nestedThing }}
{{# truthyThing | ? }}
  context in here isn't truthyThing, we just used it as an "if"!
{{/ truthyThing }}

… it's a super powerful feature. Perhaps too powerful for logic-less templates :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.