I'm using Underscore's template() method in BackboneJS views. I'd like to show a list of alphabet letters in my view in order to sort a collection by letter.
As a result, I have a list of 26 links (one link = one letter) in my view. Instead of copy-pasting each link (which is very bad for code maintainability), I was wondering if it was possible to loop through the alphabet via underscoreJS.
Result to display :
<li ><a href="#">a</a></li>
<li ><a href="#">b</a></li>
<li ><a href="#">c</a></li>
...
<li ><a href="#">z</a></li>
each. The _each method does exactly what it sounds like. It works on collections (arrays or objects), and will iterate over each element in the collection invoking the function you specified with 3 arguments (value, index, list) with index being replaced by key if used on an object.
var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
_.each(alphabet, function(letter) {
console.log(letter);
});
That's how you could do it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With