24

I am using the mustache template engine and I only want to display the first item in a long list but cant seem to find the docs for doing so?

if I use:

{{# links}}<a href="{{& url}}">{{& title }}</a>{{/ links}}

i get all of the links, however i only want the first one to be displayed, sounds easy but I cant find any docs on this.

Alex
  • 3,732
  • 5
  • 37
  • 59
  • Can you set the following answer as the right one? http://stackoverflow.com/a/17950970/171711 – Coyote Nov 20 '13 at 19:57

3 Answers3

45

This solution is working with the new version of Mustache.js (only):

mustache.render("{{a.0}}", {a: ['hi','world']})
=> 'hi'
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
Millad
  • 1,535
  • 1
  • 16
  • 17
4

The solution @Millad presented almost worked for me. Using handlebars.js though I had to use it with brackets.

{{ a.[0] }}

=> hello

res.render('view', { a: ['hello', 'world'] })
arc
  • 4,553
  • 5
  • 34
  • 43
2

Mustache has does not have logic, from the docs:

We call it "logic-less" because there are no if statements, else clauses, or for loops. Instead there are only tags. Some tags are replaced with a value, some nothing, and others a series of values. This document explains the different types of Mustache tags.

So what you essentially want is a mechanism to do an if link is the first - so you can handle this on the data side, by only putting 1 element in your data, or by adding a chunk of data like when you're putting your data in you add a value like display and set it to 'inline' or 'none' then in your template do:

{{# links}}<a href="{{& url}}" style="display: {{display}};">{{& title }}</a>{{/ links}}

Then, later, you can call scripting in page to change the style.display on some user or application action.

Those are my first though it may simply be easier to set data = data[0] for this particular template. The problem is you probably WANT to use that whole list at some point, to comment on that I'd need to see more your usage and where the data's populating from.

artlung
  • 33,305
  • 16
  • 69
  • 121
  • Thanks for this.. I can see what youre saying but it seems strange. I've done what youve suggested and altered the model pre-render. Thanks – Alex Jun 21 '12 at 22:17
  • Yeah, the idea is that Mustache is fast, but it doesn't have the logical overhead of other templating libraries. You might look at other templating libraries if Mustache is not fitting your needs. There's good discussion here: http://www.quora.com/JavaScript/What-is-the-best-JavaScript-templating-framework-and-why – artlung Jun 21 '12 at 22:24