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
Using underscore.js
and jQuery
in conjunction will help you acheive this (underscore.js is incapable of doing DOM insertion/manipulation by itself).
var abc = ['a', 'b', 'c', 'd']; //i disregarded how you get the list of letters.
_.each(abc, function(letter){
$('ul').append('<li><a href="#">'+letter+'</a></li>');
});
Also made a fiddle for you
Underscore don't have such ability, but your case could do some trick on the template. change your template like this:
<% for(var i=65; i<90; i++) { %>
<li ><a href="#"><% print(String.fromCharCode(i)); %></a></li>
<% } %>
this should be what you want.
Another approach with underscore (or loadash):
_.map(_.range(26), function(i) { return String.fromCharCode(97 + i) });
// returns ['a', 'b', ..., 'z']
var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
_.each(alphabet, function(letter) {
console.log(letter);
});
That's how you could do it.
for(let char of "abcdefghijklmnopqrstuvwxyz" )
console.log(char); // prints 'a' to 'z'
Pretty easy to use that in a template, and you could use Babel to transpile it to code for browsers which lack support for that syntax.
Create a range with the charcodes
var alphas = _.range(
'a'.charCodeAt(0),
'z'.charCodeAt(0)+1
);
// [97 .. 122]
Create an array with the letters
var letters = _.map(alphas, a => String.fromCharCode(a));
// see @deefour comment
// Non ES6 version
// var letters = _.map(alphas, function(a) {
// return String.fromCharCode(a);
// });
// [a .. z]
Inject into your template
var tpl =
'<ul>'+
'<% _.each(letters, function(letter) { %>'+
'<li><%= letter %></li>'+
'<% }); %>'+
'</ul>';
var compiled = _.template(tpl);
var html = compiled({letters : letters});
And a demo http://jsfiddle.net/hPdSQ/17/
var alphas = _.range(
'a'.charCodeAt(0),
'z'.charCodeAt(0)+1
);
var letters = _.map(alphas, a => String.fromCharCode(a));
var tpl =
'<ul>'+
'<% _.each(letters, function(letter) { %>'+
'<li><%= letter %></li>'+
'<% }); %>'+
'</ul>';
var compiled = _.template(tpl);
var html = compiled({letters : letters});
document.getElementById('res').innerHTML = html;
<script src="http://underscorejs.org/underscore-min.js"></script>
<div id='res'></div>