mirror of
https://github.com/janishutz/color-thief.git
synced 2025-11-26 22:34:25 +00:00
Updated demo page. Added package.json and bower.json.
This commit is contained in:
@@ -98,10 +98,10 @@ ColorThief.prototype.getPalette = function(sourceImage, colorCount, quality) {
|
||||
|
||||
if (typeof colorCount === 'undefined') {
|
||||
colorCount = 10;
|
||||
};
|
||||
}
|
||||
if (typeof quality === 'undefined') {
|
||||
quality = 10;
|
||||
};
|
||||
}
|
||||
|
||||
// Create custom CanvasImage object
|
||||
var image = new CanvasImage(sourceImage);
|
||||
@@ -154,18 +154,14 @@ if (!pv) {
|
||||
var pv = {
|
||||
map: function(array, f) {
|
||||
var o = {};
|
||||
return f
|
||||
? array.map(function(d, i) { o.index = i; return f.call(o, d); })
|
||||
: array.slice();
|
||||
return f ? array.map(function(d, i) { o.index = i; return f.call(o, d); }) : array.slice();
|
||||
},
|
||||
naturalOrder: function(a, b) {
|
||||
return (a < b) ? -1 : ((a > b) ? 1 : 0);
|
||||
},
|
||||
sum: function(array, f) {
|
||||
var o = {};
|
||||
return array.reduce(f
|
||||
? function(p, d, i) { o.index = i; return p + f.call(o, d); }
|
||||
: function(p, d) { return p + d; }, 0);
|
||||
return array.reduce(f ? function(p, d, i) { o.index = i; return p + f.call(o, d); } : function(p, d) { return p + d; }, 0);
|
||||
},
|
||||
max: function(array, f) {
|
||||
return Math.max.apply(null, f ? pv.map(array, f) : array);
|
||||
@@ -341,8 +337,8 @@ var MMCQ = (function() {
|
||||
return pv.naturalOrder(
|
||||
a.vbox.count()*a.vbox.volume(),
|
||||
b.vbox.count()*b.vbox.volume()
|
||||
)
|
||||
});;
|
||||
);
|
||||
});
|
||||
}
|
||||
CMap.prototype = {
|
||||
push: function(vbox) {
|
||||
@@ -352,7 +348,7 @@ var MMCQ = (function() {
|
||||
});
|
||||
},
|
||||
palette: function() {
|
||||
return this.vboxes.map(function(vb) { return vb.color });
|
||||
return this.vboxes.map(function(vb) { return vb.color; });
|
||||
},
|
||||
size: function() {
|
||||
return this.vboxes.size();
|
||||
@@ -385,7 +381,7 @@ var MMCQ = (function() {
|
||||
forcebw: function() {
|
||||
// XXX: won't work yet
|
||||
var vboxes = this.vboxes;
|
||||
vboxes.sort(function(a,b) { return pv.naturalOrder(pv.sum(a.color), pv.sum(b.color) )});
|
||||
vboxes.sort(function(a,b) { return pv.naturalOrder(pv.sum(a.color), pv.sum(b.color));});
|
||||
|
||||
// force darkest color to black if everything < 5
|
||||
var lowest = vboxes[0].color;
|
||||
@@ -445,7 +441,7 @@ var MMCQ = (function() {
|
||||
maxw = pv.max([rw, gw, bw]);
|
||||
// only one pixel, no split
|
||||
if (vbox.count() == 1) {
|
||||
return [vbox.copy()]
|
||||
return [vbox.copy()];
|
||||
}
|
||||
/* Find the partial sum arrays along the selected axis. */
|
||||
var total = 0,
|
||||
@@ -492,7 +488,7 @@ var MMCQ = (function() {
|
||||
}
|
||||
}
|
||||
partialsum.forEach(function(d,i) {
|
||||
lookaheadsum[i] = total-d
|
||||
lookaheadsum[i] = total-d;
|
||||
});
|
||||
function doCut(color) {
|
||||
var dim1 = color + '1',
|
||||
@@ -540,14 +536,14 @@ var MMCQ = (function() {
|
||||
|
||||
// check that we aren't below maxcolors already
|
||||
var nColors = 0;
|
||||
histo.forEach(function() { nColors++ });
|
||||
histo.forEach(function() { nColors++; });
|
||||
if (nColors <= maxcolors) {
|
||||
// XXX: generate the new colors from the histo and return
|
||||
}
|
||||
|
||||
// get the beginning vbox from the colors
|
||||
var vbox = vboxFromPixels(pixels, histo),
|
||||
pq = new PQueue(function(a,b) { return pv.naturalOrder(a.count(), b.count()) });
|
||||
pq = new PQueue(function(a,b) { return pv.naturalOrder(a.count(), b.count()); });
|
||||
pq.push(vbox);
|
||||
|
||||
// inner function to do the iteration
|
||||
@@ -589,7 +585,7 @@ var MMCQ = (function() {
|
||||
|
||||
// Re-sort by the product of pixel occupancy times the size in color space.
|
||||
var pq2 = new PQueue(function(a,b) {
|
||||
return pv.naturalOrder(a.count()*a.volume(), b.count()*b.volume())
|
||||
return pv.naturalOrder(a.count()*a.volume(), b.count()*b.volume());
|
||||
});
|
||||
while (pq.size()) {
|
||||
pq2.push(pq.pop());
|
||||
@@ -609,5 +605,5 @@ var MMCQ = (function() {
|
||||
|
||||
return {
|
||||
quantize: quantize
|
||||
}
|
||||
};
|
||||
})();
|
||||
|
||||
27
js/color-thief.min.js
vendored
Normal file
27
js/color-thief.min.js
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
/*!
|
||||
* Color Thief v2.0
|
||||
* by Lokesh Dhakar - http://www.lokeshdhakar.com
|
||||
*
|
||||
* License
|
||||
* -------
|
||||
* Creative Commons Attribution 2.5 License:
|
||||
* http://creativecommons.org/licenses/by/2.5/
|
||||
*
|
||||
* Thanks
|
||||
* ------
|
||||
* Nick Rabinowitz - For creating quantize.js.
|
||||
* John Schulz - For clean up and optimization. @JFSIII
|
||||
* Nathan Spady - For adding drag and drop support to the demo page.
|
||||
*
|
||||
*/
|
||||
var CanvasImage=function(a){this.canvas=document.createElement("canvas"),this.context=this.canvas.getContext("2d"),document.body.appendChild(this.canvas),this.width=this.canvas.width=a.width,this.height=this.canvas.height=a.height,this.context.drawImage(a,0,0,this.width,this.height)};CanvasImage.prototype.clear=function(){this.context.clearRect(0,0,this.width,this.height)},CanvasImage.prototype.update=function(a){this.context.putImageData(a,0,0)},CanvasImage.prototype.getPixelCount=function(){return this.width*this.height},CanvasImage.prototype.getImageData=function(){return this.context.getImageData(0,0,this.width,this.height)},CanvasImage.prototype.removeCanvas=function(){this.canvas.parentNode.removeChild(this.canvas)};var ColorThief=function(){};/*!
|
||||
* quantize.js Copyright 2008 Nick Rabinowitz.
|
||||
* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
|
||||
*/
|
||||
/*!
|
||||
* Block below copied from Protovis: http://mbostock.github.com/protovis/
|
||||
* Copyright 2010 Stanford Visualization Group
|
||||
* Licensed under the BSD License: http://www.opensource.org/licenses/bsd-license.php
|
||||
*/
|
||||
if(ColorThief.prototype.getColor=function(a,b){var c=this.getPalette(a,5,b),d=c[0];return d},ColorThief.prototype.getPalette=function(a,b,c){"undefined"==typeof b&&(b=10),"undefined"==typeof c&&(c=10);for(var d,e,f,g,h,i=new CanvasImage(a),j=i.getImageData(),k=j.data,l=i.getPixelCount(),m=[],n=0;l>n;n+=c)d=4*n,e=k[d+0],f=k[d+1],g=k[d+2],h=k[d+3],h>=125&&(e>250&&f>250&&g>250||m.push([e,f,g]));var o=MMCQ.quantize(m,b),p=o.palette();return i.removeCanvas(),p},!pv)var pv={map:function(a,b){var c={};return b?a.map(function(a,d){return c.index=d,b.call(c,a)}):a.slice()},naturalOrder:function(a,b){return b>a?-1:a>b?1:0},sum:function(a,b){var c={};return a.reduce(b?function(a,d,e){return c.index=e,a+b.call(c,d)}:function(a,b){return a+b},0)},max:function(a,b){return Math.max.apply(null,b?pv.map(a,b):a)}};var MMCQ=function(){function a(a,b,c){return(a<<2*i)+(b<<i)+c}function b(a){function b(){c.sort(a),d=!0}var c=[],d=!1;return{push:function(a){c.push(a),d=!1},peek:function(a){return d||b(),void 0===a&&(a=c.length-1),c[a]},pop:function(){return d||b(),c.pop()},size:function(){return c.length},map:function(a){return c.map(a)},debug:function(){return d||b(),c}}}function c(a,b,c,d,e,f,g){var h=this;h.r1=a,h.r2=b,h.g1=c,h.g2=d,h.b1=e,h.b2=f,h.histo=g}function d(){this.vboxes=new b(function(a,b){return pv.naturalOrder(a.vbox.count()*a.vbox.volume(),b.vbox.count()*b.vbox.volume())})}function e(b){var c,d,e,f,g=1<<3*i,h=new Array(g);return b.forEach(function(b){d=b[0]>>j,e=b[1]>>j,f=b[2]>>j,c=a(d,e,f),h[c]=(h[c]||0)+1}),h}function f(a,b){var d,e,f,g=1e6,h=0,i=1e6,k=0,l=1e6,m=0;return a.forEach(function(a){d=a[0]>>j,e=a[1]>>j,f=a[2]>>j,g>d?g=d:d>h&&(h=d),i>e?i=e:e>k&&(k=e),l>f?l=f:f>m&&(m=f)}),new c(g,h,i,k,l,m,b)}function g(b,c){function d(a){var b,d,e,f,g,h=a+"1",j=a+"2",k=0;for(i=c[h];i<=c[j];i++)if(o[i]>n/2){for(e=c.copy(),f=c.copy(),b=i-c[h],d=c[j]-i,g=d>=b?Math.min(c[j]-1,~~(i+d/2)):Math.max(c[h],~~(i-1-b/2));!o[g];)g++;for(k=p[g];!k&&o[g-1];)k=p[--g];return e[j]=g,f[h]=e[j]+1,[e,f]}}if(c.count()){var e=c.r2-c.r1+1,f=c.g2-c.g1+1,g=c.b2-c.b1+1,h=pv.max([e,f,g]);if(1==c.count())return[c.copy()];var i,j,k,l,m,n=0,o=[],p=[];if(h==e)for(i=c.r1;i<=c.r2;i++){for(l=0,j=c.g1;j<=c.g2;j++)for(k=c.b1;k<=c.b2;k++)m=a(i,j,k),l+=b[m]||0;n+=l,o[i]=n}else if(h==f)for(i=c.g1;i<=c.g2;i++){for(l=0,j=c.r1;j<=c.r2;j++)for(k=c.b1;k<=c.b2;k++)m=a(j,i,k),l+=b[m]||0;n+=l,o[i]=n}else for(i=c.b1;i<=c.b2;i++){for(l=0,j=c.r1;j<=c.r2;j++)for(k=c.g1;k<=c.g2;k++)m=a(j,k,i),l+=b[m]||0;n+=l,o[i]=n}return o.forEach(function(a,b){p[b]=n-a}),d(h==e?"r":h==f?"g":"b")}}function h(a,c){function h(a,b){for(var c,d=1,e=0;k>e;)if(c=a.pop(),c.count()){var f=g(i,c),h=f[0],j=f[1];if(!h)return;if(a.push(h),j&&(a.push(j),d++),d>=b)return;if(e++>k)return}else a.push(c),e++}if(!a.length||2>c||c>256)return!1;var i=e(a),j=0;i.forEach(function(){j++});var m=f(a,i),n=new b(function(a,b){return pv.naturalOrder(a.count(),b.count())});n.push(m),h(n,l*c);for(var o=new b(function(a,b){return pv.naturalOrder(a.count()*a.volume(),b.count()*b.volume())});n.size();)o.push(n.pop());h(o,c-o.size());for(var p=new d;o.size();)p.push(o.pop());return p}var i=5,j=8-i,k=1e3,l=.75;return c.prototype={volume:function(a){var b=this;return(!b._volume||a)&&(b._volume=(b.r2-b.r1+1)*(b.g2-b.g1+1)*(b.b2-b.b1+1)),b._volume},count:function(b){var c=this,d=c.histo;if(!c._count_set||b){var e,f,g,h=0;for(e=c.r1;e<=c.r2;e++)for(f=c.g1;f<=c.g2;f++)for(g=c.b1;g<=c.b2;g++)index=a(e,f,g),h+=d[index]||0;c._count=h,c._count_set=!0}return c._count},copy:function(){var a=this;return new c(a.r1,a.r2,a.g1,a.g2,a.b1,a.b2,a.histo)},avg:function(b){var c=this,d=c.histo;if(!c._avg||b){var e,f,g,h,j,k=0,l=1<<8-i,m=0,n=0,o=0;for(f=c.r1;f<=c.r2;f++)for(g=c.g1;g<=c.g2;g++)for(h=c.b1;h<=c.b2;h++)j=a(f,g,h),e=d[j]||0,k+=e,m+=e*(f+.5)*l,n+=e*(g+.5)*l,o+=e*(h+.5)*l;c._avg=k?[~~(m/k),~~(n/k),~~(o/k)]:[~~(l*(c.r1+c.r2+1)/2),~~(l*(c.g1+c.g2+1)/2),~~(l*(c.b1+c.b2+1)/2)]}return c._avg},contains:function(a){var b=this,c=a[0]>>j;return gval=a[1]>>j,bval=a[2]>>j,c>=b.r1&&c<=b.r2&&gval>=b.g1&&gval<=b.g2&&bval>=b.b1&&bval<=b.b2}},d.prototype={push:function(a){this.vboxes.push({vbox:a,color:a.avg()})},palette:function(){return this.vboxes.map(function(a){return a.color})},size:function(){return this.vboxes.size()},map:function(a){for(var b=this.vboxes,c=0;c<b.size();c++)if(b.peek(c).vbox.contains(a))return b.peek(c).color;return this.nearest(a)},nearest:function(a){for(var b,c,d,e=this.vboxes,f=0;f<e.size();f++)c=Math.sqrt(Math.pow(a[0]-e.peek(f).color[0],2)+Math.pow(a[1]-e.peek(f).color[1],2)+Math.pow(a[2]-e.peek(f).color[2],2)),(b>c||void 0===b)&&(b=c,d=e.peek(f).color);return d},forcebw:function(){var a=this.vboxes;a.sort(function(a,b){return pv.naturalOrder(pv.sum(a.color),pv.sum(b.color))});var b=a[0].color;b[0]<5&&b[1]<5&&b[2]<5&&(a[0].color=[0,0,0]);var c=a.length-1,d=a[c].color;d[0]>251&&d[1]>251&&d[2]>251&&(a[c].color=[255,255,255])}},{quantize:h}}();
|
||||
//# sourceMappingURL=color-thief.min.map
|
||||
1
js/color-thief.min.map
Normal file
1
js/color-thief.min.map
Normal file
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
9111
js/jquery.js
vendored
Normal file
9111
js/jquery.js
vendored
Normal file
File diff suppressed because it is too large
Load Diff
6
js/libs/jquery-2.0.2.min.js
vendored
6
js/libs/jquery-2.0.2.min.js
vendored
File diff suppressed because one or more lines are too long
@@ -1,66 +0,0 @@
|
||||
/*global jQuery */
|
||||
/*!
|
||||
* Lettering.JS 0.6.1
|
||||
*
|
||||
* Copyright 2010, Dave Rupert http://daverupert.com
|
||||
* Released under the WTFPL license
|
||||
* http://sam.zoy.org/wtfpl/
|
||||
*
|
||||
* Thanks to Paul Irish - http://paulirish.com - for the feedback.
|
||||
*
|
||||
* Date: Mon Sep 20 17:14:00 2010 -0600
|
||||
*/
|
||||
(function($){
|
||||
function injector(t, splitter, klass, after) {
|
||||
var a = t.text().split(splitter), inject = '';
|
||||
if (a.length) {
|
||||
$(a).each(function(i, item) {
|
||||
inject += '<span class="'+klass+(i+1)+'">'+item+'</span>'+after;
|
||||
});
|
||||
t.empty().append(inject);
|
||||
}
|
||||
}
|
||||
|
||||
var methods = {
|
||||
init : function() {
|
||||
|
||||
return this.each(function() {
|
||||
injector($(this), '', 'char', '');
|
||||
});
|
||||
|
||||
},
|
||||
|
||||
words : function() {
|
||||
|
||||
return this.each(function() {
|
||||
injector($(this), ' ', 'word', ' ');
|
||||
});
|
||||
|
||||
},
|
||||
|
||||
lines : function() {
|
||||
|
||||
return this.each(function() {
|
||||
var r = "eefec303079ad17405c889e092e105b0";
|
||||
// Because it's hard to split a <br/> tag consistently across browsers,
|
||||
// (*ahem* IE *ahem*), we replaces all <br/> instances with an md5 hash
|
||||
// (of the word "split"). If you're trying to use this plugin on that
|
||||
// md5 hash string, it will fail because you're being ridiculous.
|
||||
injector($(this).children("br").replaceWith(r).end(), r, 'line', '');
|
||||
});
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
$.fn.lettering = function( method ) {
|
||||
// Method calling logic
|
||||
if ( method && methods[method] ) {
|
||||
return methods[ method ].apply( this, [].slice.call( arguments, 1 ));
|
||||
} else if ( method === 'letters' || ! method ) {
|
||||
return methods.init.apply( this, [].slice.call( arguments, 0 ) ); // always pass an array
|
||||
}
|
||||
$.error( 'Method ' + method + ' does not exist on jQuery.lettering' );
|
||||
return this;
|
||||
};
|
||||
|
||||
})(jQuery);
|
||||
@@ -1,419 +0,0 @@
|
||||
/*
|
||||
mustache.js — Logic-less templates in JavaScript
|
||||
|
||||
See http://mustache.github.com/ for more info.
|
||||
*/
|
||||
|
||||
var Mustache = function() {
|
||||
var regexCache = {};
|
||||
var Renderer = function() {};
|
||||
|
||||
Renderer.prototype = {
|
||||
otag: "{{",
|
||||
ctag: "}}",
|
||||
pragmas: {},
|
||||
buffer: [],
|
||||
pragmas_implemented: {
|
||||
"IMPLICIT-ITERATOR": true
|
||||
},
|
||||
context: {},
|
||||
|
||||
render: function(template, context, partials, in_recursion) {
|
||||
// reset buffer & set context
|
||||
if(!in_recursion) {
|
||||
this.context = context;
|
||||
this.buffer = []; // TODO: make this non-lazy
|
||||
}
|
||||
|
||||
// fail fast
|
||||
if(!this.includes("", template)) {
|
||||
if(in_recursion) {
|
||||
return template;
|
||||
} else {
|
||||
this.send(template);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// get the pragmas together
|
||||
template = this.render_pragmas(template);
|
||||
|
||||
// render the template
|
||||
var html = this.render_section(template, context, partials);
|
||||
|
||||
// render_section did not find any sections, we still need to render the tags
|
||||
if (html === false) {
|
||||
html = this.render_tags(template, context, partials, in_recursion);
|
||||
}
|
||||
|
||||
if (in_recursion) {
|
||||
return html;
|
||||
} else {
|
||||
this.sendLines(html);
|
||||
}
|
||||
},
|
||||
|
||||
/*
|
||||
Sends parsed lines
|
||||
*/
|
||||
send: function(line) {
|
||||
if(line !== "") {
|
||||
this.buffer.push(line);
|
||||
}
|
||||
},
|
||||
|
||||
sendLines: function(text) {
|
||||
if (text) {
|
||||
var lines = text.split("\n");
|
||||
for (var i = 0; i < lines.length; i++) {
|
||||
this.send(lines[i]);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/*
|
||||
Looks for %PRAGMAS
|
||||
*/
|
||||
render_pragmas: function(template) {
|
||||
// no pragmas
|
||||
if(!this.includes("%", template)) {
|
||||
return template;
|
||||
}
|
||||
|
||||
var that = this;
|
||||
var regex = this.getCachedRegex("render_pragmas", function(otag, ctag) {
|
||||
return new RegExp(otag + "%([\\w-]+) ?([\\w]+=[\\w]+)?" + ctag, "g");
|
||||
});
|
||||
|
||||
return template.replace(regex, function(match, pragma, options) {
|
||||
if(!that.pragmas_implemented[pragma]) {
|
||||
throw({message:
|
||||
"This implementation of mustache doesn't understand the '" +
|
||||
pragma + "' pragma"});
|
||||
}
|
||||
that.pragmas[pragma] = {};
|
||||
if(options) {
|
||||
var opts = options.split("=");
|
||||
that.pragmas[pragma][opts[0]] = opts[1];
|
||||
}
|
||||
return "";
|
||||
// ignore unknown pragmas silently
|
||||
});
|
||||
},
|
||||
|
||||
/*
|
||||
Tries to find a partial in the curent scope and render it
|
||||
*/
|
||||
render_partial: function(name, context, partials) {
|
||||
name = this.trim(name);
|
||||
if(!partials || partials[name] === undefined) {
|
||||
throw({message: "unknown_partial '" + name + "'"});
|
||||
}
|
||||
if(typeof(context[name]) != "object") {
|
||||
return this.render(partials[name], context, partials, true);
|
||||
}
|
||||
return this.render(partials[name], context[name], partials, true);
|
||||
},
|
||||
|
||||
/*
|
||||
Renders inverted (^) and normal (#) sections
|
||||
*/
|
||||
render_section: function(template, context, partials) {
|
||||
if(!this.includes("#", template) && !this.includes("^", template)) {
|
||||
// did not render anything, there were no sections
|
||||
return false;
|
||||
}
|
||||
|
||||
var that = this;
|
||||
|
||||
var regex = this.getCachedRegex("render_section", function(otag, ctag) {
|
||||
// This regex matches _the first_ section ({{#foo}}{{/foo}}), and captures the remainder
|
||||
return new RegExp(
|
||||
"^([\\s\\S]*?)" + // all the crap at the beginning that is not {{*}} ($1)
|
||||
|
||||
otag + // {{
|
||||
"(\\^|\\#)\\s*(.+)\\s*" + // #foo (# == $2, foo == $3)
|
||||
ctag + // }}
|
||||
|
||||
"\n*([\\s\\S]*?)" + // between the tag ($2). leading newlines are dropped
|
||||
|
||||
otag + // {{
|
||||
"\\/\\s*\\3\\s*" + // /foo (backreference to the opening tag).
|
||||
ctag + // }}
|
||||
|
||||
"\\s*([\\s\\S]*)$", // everything else in the string ($4). leading whitespace is dropped.
|
||||
|
||||
"g");
|
||||
});
|
||||
|
||||
|
||||
// for each {{#foo}}{{/foo}} section do...
|
||||
return template.replace(regex, function(match, before, type, name, content, after) {
|
||||
// before contains only tags, no sections
|
||||
var renderedBefore = before ? that.render_tags(before, context, partials, true) : "",
|
||||
|
||||
// after may contain both sections and tags, so use full rendering function
|
||||
renderedAfter = after ? that.render(after, context, partials, true) : "",
|
||||
|
||||
// will be computed below
|
||||
renderedContent,
|
||||
|
||||
value = that.find(name, context);
|
||||
|
||||
if (type === "^") { // inverted section
|
||||
if (!value || that.is_array(value) && value.length === 0) {
|
||||
// false or empty list, render it
|
||||
renderedContent = that.render(content, context, partials, true);
|
||||
} else {
|
||||
renderedContent = "";
|
||||
}
|
||||
} else if (type === "#") { // normal section
|
||||
if (that.is_array(value)) { // Enumerable, Let's loop!
|
||||
renderedContent = that.map(value, function(row) {
|
||||
return that.render(content, that.create_context(row), partials, true);
|
||||
}).join("");
|
||||
} else if (that.is_object(value)) { // Object, Use it as subcontext!
|
||||
renderedContent = that.render(content, that.create_context(value),
|
||||
partials, true);
|
||||
} else if (typeof value === "function") {
|
||||
// higher order section
|
||||
renderedContent = value.call(context, content, function(text) {
|
||||
return that.render(text, context, partials, true);
|
||||
});
|
||||
} else if (value) { // boolean section
|
||||
renderedContent = that.render(content, context, partials, true);
|
||||
} else {
|
||||
renderedContent = "";
|
||||
}
|
||||
}
|
||||
|
||||
return renderedBefore + renderedContent + renderedAfter;
|
||||
});
|
||||
},
|
||||
|
||||
/*
|
||||
Replace {{foo}} and friends with values from our view
|
||||
*/
|
||||
render_tags: function(template, context, partials, in_recursion) {
|
||||
// tit for tat
|
||||
var that = this;
|
||||
|
||||
|
||||
|
||||
var new_regex = function() {
|
||||
return that.getCachedRegex("render_tags", function(otag, ctag) {
|
||||
return new RegExp(otag + "(=|!|>|\\{|%)?([^\\/#\\^]+?)\\1?" + ctag + "+", "g");
|
||||
});
|
||||
};
|
||||
|
||||
var regex = new_regex();
|
||||
var tag_replace_callback = function(match, operator, name) {
|
||||
switch(operator) {
|
||||
case "!": // ignore comments
|
||||
return "";
|
||||
case "=": // set new delimiters, rebuild the replace regexp
|
||||
that.set_delimiters(name);
|
||||
regex = new_regex();
|
||||
return "";
|
||||
case ">": // render partial
|
||||
return that.render_partial(name, context, partials);
|
||||
case "{": // the triple mustache is unescaped
|
||||
return that.find(name, context);
|
||||
default: // escape the value
|
||||
return that.escape(that.find(name, context));
|
||||
}
|
||||
};
|
||||
var lines = template.split("\n");
|
||||
for(var i = 0; i < lines.length; i++) {
|
||||
lines[i] = lines[i].replace(regex, tag_replace_callback, this);
|
||||
if(!in_recursion) {
|
||||
this.send(lines[i]);
|
||||
}
|
||||
}
|
||||
|
||||
if(in_recursion) {
|
||||
return lines.join("\n");
|
||||
}
|
||||
},
|
||||
|
||||
set_delimiters: function(delimiters) {
|
||||
var dels = delimiters.split(" ");
|
||||
this.otag = this.escape_regex(dels[0]);
|
||||
this.ctag = this.escape_regex(dels[1]);
|
||||
},
|
||||
|
||||
escape_regex: function(text) {
|
||||
// thank you Simon Willison
|
||||
if(!arguments.callee.sRE) {
|
||||
var specials = [
|
||||
'/', '.', '*', '+', '?', '|',
|
||||
'(', ')', '[', ']', '{', '}', '\\'
|
||||
];
|
||||
arguments.callee.sRE = new RegExp(
|
||||
'(\\' + specials.join('|\\') + ')', 'g'
|
||||
);
|
||||
}
|
||||
return text.replace(arguments.callee.sRE, '\\$1');
|
||||
},
|
||||
|
||||
/*
|
||||
find `name` in current `context`. That is find me a value
|
||||
from the view object
|
||||
*/
|
||||
find: function(name, context) {
|
||||
name = this.trim(name);
|
||||
|
||||
// Checks whether a value is thruthy or false or 0
|
||||
function is_kinda_truthy(bool) {
|
||||
return bool === false || bool === 0 || bool;
|
||||
}
|
||||
|
||||
var value;
|
||||
|
||||
// check for dot notation eg. foo.bar
|
||||
if(name.match(/([a-z_]+)\./ig)){
|
||||
value = is_kinda_truthy(this.walk_context(name, context));
|
||||
}
|
||||
else{
|
||||
if(is_kinda_truthy(context[name])) {
|
||||
value = context[name];
|
||||
} else if(is_kinda_truthy(this.context[name])) {
|
||||
value = this.context[name];
|
||||
}
|
||||
}
|
||||
|
||||
if(typeof value === "function") {
|
||||
return value.apply(context);
|
||||
}
|
||||
if(value !== undefined) {
|
||||
return value;
|
||||
}
|
||||
// silently ignore unkown variables
|
||||
return "";
|
||||
},
|
||||
|
||||
walk_context: function(name, context){
|
||||
var path = name.split('.');
|
||||
// if the var doesn't exist in current context, check the top level context
|
||||
var value_context = (context[path[0]] != undefined) ? context : this.context;
|
||||
var value = value_context[path.shift()];
|
||||
while(value != undefined && path.length > 0){
|
||||
value_context = value;
|
||||
value = value[path.shift()];
|
||||
}
|
||||
// if the value is a function, call it, binding the correct context
|
||||
if(typeof value === "function") {
|
||||
return value.apply(value_context);
|
||||
}
|
||||
return value;
|
||||
},
|
||||
|
||||
// Utility methods
|
||||
|
||||
/* includes tag */
|
||||
includes: function(needle, haystack) {
|
||||
return haystack.indexOf(this.otag + needle) != -1;
|
||||
},
|
||||
|
||||
/*
|
||||
Does away with nasty characters
|
||||
*/
|
||||
escape: function(s) {
|
||||
s = String(s === null ? "" : s);
|
||||
return s.replace(/&(?!\w+;)|["'<>\\]/g, function(s) {
|
||||
switch(s) {
|
||||
case "&": return "&";
|
||||
case '"': return '"';
|
||||
case "'": return ''';
|
||||
case "<": return "<";
|
||||
case ">": return ">";
|
||||
default: return s;
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
// by @langalex, support for arrays of strings
|
||||
create_context: function(_context) {
|
||||
if(this.is_object(_context)) {
|
||||
return _context;
|
||||
} else {
|
||||
var iterator = ".";
|
||||
if(this.pragmas["IMPLICIT-ITERATOR"]) {
|
||||
iterator = this.pragmas["IMPLICIT-ITERATOR"].iterator;
|
||||
}
|
||||
var ctx = {};
|
||||
ctx[iterator] = _context;
|
||||
return ctx;
|
||||
}
|
||||
},
|
||||
|
||||
is_object: function(a) {
|
||||
return a && typeof a == "object";
|
||||
},
|
||||
|
||||
is_array: function(a) {
|
||||
return Object.prototype.toString.call(a) === '[object Array]';
|
||||
},
|
||||
|
||||
/*
|
||||
Gets rid of leading and trailing whitespace
|
||||
*/
|
||||
trim: function(s) {
|
||||
return s.replace(/^\s*|\s*$/g, "");
|
||||
},
|
||||
|
||||
/*
|
||||
Why, why, why? Because IE. Cry, cry cry.
|
||||
*/
|
||||
map: function(array, fn) {
|
||||
if (typeof array.map == "function") {
|
||||
return array.map(fn);
|
||||
} else {
|
||||
var r = [];
|
||||
var l = array.length;
|
||||
for(var i = 0; i < l; i++) {
|
||||
r.push(fn(array[i]));
|
||||
}
|
||||
return r;
|
||||
}
|
||||
},
|
||||
|
||||
getCachedRegex: function(name, generator) {
|
||||
var byOtag = regexCache[this.otag];
|
||||
if (!byOtag) {
|
||||
byOtag = regexCache[this.otag] = {};
|
||||
}
|
||||
|
||||
var byCtag = byOtag[this.ctag];
|
||||
if (!byCtag) {
|
||||
byCtag = byOtag[this.ctag] = {};
|
||||
}
|
||||
|
||||
var regex = byCtag[name];
|
||||
if (!regex) {
|
||||
regex = byCtag[name] = generator(this.otag, this.ctag);
|
||||
}
|
||||
|
||||
return regex;
|
||||
}
|
||||
};
|
||||
|
||||
return({
|
||||
name: "mustache.js",
|
||||
version: "0.4.0-dev",
|
||||
|
||||
/*
|
||||
Turns a template and view into HTML
|
||||
*/
|
||||
to_html: function(template, view, partials, send_fun) {
|
||||
var renderer = new Renderer();
|
||||
if(send_fun) {
|
||||
renderer.send = send_fun;
|
||||
}
|
||||
renderer.render(template, view || {}, partials);
|
||||
if(!send_fun) {
|
||||
return renderer.buffer.join("\n");
|
||||
}
|
||||
}
|
||||
});
|
||||
}();
|
||||
570
js/mustache.js
Normal file
570
js/mustache.js
Normal file
@@ -0,0 +1,570 @@
|
||||
/*!
|
||||
* mustache.js - Logic-less {{mustache}} templates with JavaScript
|
||||
* http://github.com/janl/mustache.js
|
||||
*/
|
||||
|
||||
/*global define: false*/
|
||||
|
||||
(function (root, factory) {
|
||||
if (typeof exports === "object" && exports) {
|
||||
factory(exports); // CommonJS
|
||||
} else {
|
||||
var mustache = {};
|
||||
factory(mustache);
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(mustache); // AMD
|
||||
} else {
|
||||
root.Mustache = mustache; // <script>
|
||||
}
|
||||
}
|
||||
}(this, function (mustache) {
|
||||
|
||||
var whiteRe = /\s*/;
|
||||
var spaceRe = /\s+/;
|
||||
var nonSpaceRe = /\S/;
|
||||
var eqRe = /\s*=/;
|
||||
var curlyRe = /\s*\}/;
|
||||
var tagRe = /#|\^|\/|>|\{|&|=|!/;
|
||||
|
||||
// Workaround for https://issues.apache.org/jira/browse/COUCHDB-577
|
||||
// See https://github.com/janl/mustache.js/issues/189
|
||||
var RegExp_test = RegExp.prototype.test;
|
||||
function testRegExp(re, string) {
|
||||
return RegExp_test.call(re, string);
|
||||
}
|
||||
|
||||
function isWhitespace(string) {
|
||||
return !testRegExp(nonSpaceRe, string);
|
||||
}
|
||||
|
||||
var Object_toString = Object.prototype.toString;
|
||||
var isArray = Array.isArray || function (object) {
|
||||
return Object_toString.call(object) === '[object Array]';
|
||||
};
|
||||
|
||||
function isFunction(object) {
|
||||
return typeof object === 'function';
|
||||
}
|
||||
|
||||
function escapeRegExp(string) {
|
||||
return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
|
||||
}
|
||||
|
||||
var entityMap = {
|
||||
"&": "&",
|
||||
"<": "<",
|
||||
">": ">",
|
||||
'"': '"',
|
||||
"'": ''',
|
||||
"/": '/'
|
||||
};
|
||||
|
||||
function escapeHtml(string) {
|
||||
return String(string).replace(/[&<>"'\/]/g, function (s) {
|
||||
return entityMap[s];
|
||||
});
|
||||
}
|
||||
|
||||
function escapeTags(tags) {
|
||||
if (!isArray(tags) || tags.length !== 2) {
|
||||
throw new Error('Invalid tags: ' + tags);
|
||||
}
|
||||
|
||||
return [
|
||||
new RegExp(escapeRegExp(tags[0]) + "\\s*"),
|
||||
new RegExp("\\s*" + escapeRegExp(tags[1]))
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Breaks up the given `template` string into a tree of tokens. If the `tags`
|
||||
* argument is given here it must be an array with two string values: the
|
||||
* opening and closing tags used in the template (e.g. [ "<%", "%>" ]). Of
|
||||
* course, the default is to use mustaches (i.e. mustache.tags).
|
||||
*
|
||||
* A token is an array with at least 4 elements. The first element is the
|
||||
* mustache symbol that was used inside the tag, e.g. "#" or "&". If the tag
|
||||
* did not contain a symbol (i.e. {{myValue}}) this element is "name". For
|
||||
* all template text that appears outside a symbol this element is "text".
|
||||
*
|
||||
* The second element of a token is its "value". For mustache tags this is
|
||||
* whatever else was inside the tag besides the opening symbol. For text tokens
|
||||
* this is the text itself.
|
||||
*
|
||||
* The third and fourth elements of the token are the start and end indices
|
||||
* in the original template of the token, respectively.
|
||||
*
|
||||
* Tokens that are the root node of a subtree contain two more elements: an
|
||||
* array of tokens in the subtree and the index in the original template at which
|
||||
* the closing tag for that section begins.
|
||||
*/
|
||||
function parseTemplate(template, tags) {
|
||||
tags = tags || mustache.tags;
|
||||
template = template || '';
|
||||
|
||||
if (typeof tags === 'string') {
|
||||
tags = tags.split(spaceRe);
|
||||
}
|
||||
|
||||
var tagRes = escapeTags(tags);
|
||||
var scanner = new Scanner(template);
|
||||
|
||||
var sections = []; // Stack to hold section tokens
|
||||
var tokens = []; // Buffer to hold the tokens
|
||||
var spaces = []; // Indices of whitespace tokens on the current line
|
||||
var hasTag = false; // Is there a {{tag}} on the current line?
|
||||
var nonSpace = false; // Is there a non-space char on the current line?
|
||||
|
||||
// Strips all whitespace tokens array for the current line
|
||||
// if there was a {{#tag}} on it and otherwise only space.
|
||||
function stripSpace() {
|
||||
if (hasTag && !nonSpace) {
|
||||
while (spaces.length) {
|
||||
delete tokens[spaces.pop()];
|
||||
}
|
||||
} else {
|
||||
spaces = [];
|
||||
}
|
||||
|
||||
hasTag = false;
|
||||
nonSpace = false;
|
||||
}
|
||||
|
||||
var start, type, value, chr, token, openSection;
|
||||
while (!scanner.eos()) {
|
||||
start = scanner.pos;
|
||||
|
||||
// Match any text between tags.
|
||||
value = scanner.scanUntil(tagRes[0]);
|
||||
if (value) {
|
||||
for (var i = 0, len = value.length; i < len; ++i) {
|
||||
chr = value.charAt(i);
|
||||
|
||||
if (isWhitespace(chr)) {
|
||||
spaces.push(tokens.length);
|
||||
} else {
|
||||
nonSpace = true;
|
||||
}
|
||||
|
||||
tokens.push(['text', chr, start, start + 1]);
|
||||
start += 1;
|
||||
|
||||
// Check for whitespace on the current line.
|
||||
if (chr === '\n') {
|
||||
stripSpace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Match the opening tag.
|
||||
if (!scanner.scan(tagRes[0])) break;
|
||||
hasTag = true;
|
||||
|
||||
// Get the tag type.
|
||||
type = scanner.scan(tagRe) || 'name';
|
||||
scanner.scan(whiteRe);
|
||||
|
||||
// Get the tag value.
|
||||
if (type === '=') {
|
||||
value = scanner.scanUntil(eqRe);
|
||||
scanner.scan(eqRe);
|
||||
scanner.scanUntil(tagRes[1]);
|
||||
} else if (type === '{') {
|
||||
value = scanner.scanUntil(new RegExp('\\s*' + escapeRegExp('}' + tags[1])));
|
||||
scanner.scan(curlyRe);
|
||||
scanner.scanUntil(tagRes[1]);
|
||||
type = '&';
|
||||
} else {
|
||||
value = scanner.scanUntil(tagRes[1]);
|
||||
}
|
||||
|
||||
// Match the closing tag.
|
||||
if (!scanner.scan(tagRes[1])) {
|
||||
throw new Error('Unclosed tag at ' + scanner.pos);
|
||||
}
|
||||
|
||||
token = [ type, value, start, scanner.pos ];
|
||||
tokens.push(token);
|
||||
|
||||
if (type === '#' || type === '^') {
|
||||
sections.push(token);
|
||||
} else if (type === '/') {
|
||||
// Check section nesting.
|
||||
openSection = sections.pop();
|
||||
|
||||
if (!openSection) {
|
||||
throw new Error('Unopened section "' + value + '" at ' + start);
|
||||
}
|
||||
if (openSection[1] !== value) {
|
||||
throw new Error('Unclosed section "' + openSection[1] + '" at ' + start);
|
||||
}
|
||||
} else if (type === 'name' || type === '{' || type === '&') {
|
||||
nonSpace = true;
|
||||
} else if (type === '=') {
|
||||
// Set the tags for the next time around.
|
||||
tagRes = escapeTags(tags = value.split(spaceRe));
|
||||
}
|
||||
}
|
||||
|
||||
// Make sure there are no open sections when we're done.
|
||||
openSection = sections.pop();
|
||||
if (openSection) {
|
||||
throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos);
|
||||
}
|
||||
|
||||
return nestTokens(squashTokens(tokens));
|
||||
}
|
||||
|
||||
/**
|
||||
* Combines the values of consecutive text tokens in the given `tokens` array
|
||||
* to a single token.
|
||||
*/
|
||||
function squashTokens(tokens) {
|
||||
var squashedTokens = [];
|
||||
|
||||
var token, lastToken;
|
||||
for (var i = 0, len = tokens.length; i < len; ++i) {
|
||||
token = tokens[i];
|
||||
|
||||
if (token) {
|
||||
if (token[0] === 'text' && lastToken && lastToken[0] === 'text') {
|
||||
lastToken[1] += token[1];
|
||||
lastToken[3] = token[3];
|
||||
} else {
|
||||
squashedTokens.push(token);
|
||||
lastToken = token;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return squashedTokens;
|
||||
}
|
||||
|
||||
/**
|
||||
* Forms the given array of `tokens` into a nested tree structure where
|
||||
* tokens that represent a section have two additional items: 1) an array of
|
||||
* all tokens that appear in that section and 2) the index in the original
|
||||
* template that represents the end of that section.
|
||||
*/
|
||||
function nestTokens(tokens) {
|
||||
var nestedTokens = [];
|
||||
var collector = nestedTokens;
|
||||
var sections = [];
|
||||
|
||||
var token, section;
|
||||
for (var i = 0, len = tokens.length; i < len; ++i) {
|
||||
token = tokens[i];
|
||||
|
||||
switch (token[0]) {
|
||||
case '#':
|
||||
case '^':
|
||||
collector.push(token);
|
||||
sections.push(token);
|
||||
collector = token[4] = [];
|
||||
break;
|
||||
case '/':
|
||||
section = sections.pop();
|
||||
section[5] = token[2];
|
||||
collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens;
|
||||
break;
|
||||
default:
|
||||
collector.push(token);
|
||||
}
|
||||
}
|
||||
|
||||
return nestedTokens;
|
||||
}
|
||||
|
||||
/**
|
||||
* A simple string scanner that is used by the template parser to find
|
||||
* tokens in template strings.
|
||||
*/
|
||||
function Scanner(string) {
|
||||
this.string = string;
|
||||
this.tail = string;
|
||||
this.pos = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns `true` if the tail is empty (end of string).
|
||||
*/
|
||||
Scanner.prototype.eos = function () {
|
||||
return this.tail === "";
|
||||
};
|
||||
|
||||
/**
|
||||
* Tries to match the given regular expression at the current position.
|
||||
* Returns the matched text if it can match, the empty string otherwise.
|
||||
*/
|
||||
Scanner.prototype.scan = function (re) {
|
||||
var match = this.tail.match(re);
|
||||
|
||||
if (match && match.index === 0) {
|
||||
var string = match[0];
|
||||
this.tail = this.tail.substring(string.length);
|
||||
this.pos += string.length;
|
||||
return string;
|
||||
}
|
||||
|
||||
return "";
|
||||
};
|
||||
|
||||
/**
|
||||
* Skips all text until the given regular expression can be matched. Returns
|
||||
* the skipped string, which is the entire tail if no match can be made.
|
||||
*/
|
||||
Scanner.prototype.scanUntil = function (re) {
|
||||
var index = this.tail.search(re), match;
|
||||
|
||||
switch (index) {
|
||||
case -1:
|
||||
match = this.tail;
|
||||
this.tail = "";
|
||||
break;
|
||||
case 0:
|
||||
match = "";
|
||||
break;
|
||||
default:
|
||||
match = this.tail.substring(0, index);
|
||||
this.tail = this.tail.substring(index);
|
||||
}
|
||||
|
||||
this.pos += match.length;
|
||||
|
||||
return match;
|
||||
};
|
||||
|
||||
/**
|
||||
* Represents a rendering context by wrapping a view object and
|
||||
* maintaining a reference to the parent context.
|
||||
*/
|
||||
function Context(view, parentContext) {
|
||||
this.view = view == null ? {} : view;
|
||||
this.cache = { '.': this.view };
|
||||
this.parent = parentContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new context using the given view with this context
|
||||
* as the parent.
|
||||
*/
|
||||
Context.prototype.push = function (view) {
|
||||
return new Context(view, this);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the value of the given name in this context, traversing
|
||||
* up the context hierarchy if the value is absent in this context's view.
|
||||
*/
|
||||
Context.prototype.lookup = function (name) {
|
||||
var value;
|
||||
if (name in this.cache) {
|
||||
value = this.cache[name];
|
||||
} else {
|
||||
var context = this;
|
||||
|
||||
while (context) {
|
||||
if (name.indexOf('.') > 0) {
|
||||
value = context.view;
|
||||
|
||||
var names = name.split('.'), i = 0;
|
||||
while (value != null && i < names.length) {
|
||||
value = value[names[i++]];
|
||||
}
|
||||
} else {
|
||||
value = context.view[name];
|
||||
}
|
||||
|
||||
if (value != null) break;
|
||||
|
||||
context = context.parent;
|
||||
}
|
||||
|
||||
this.cache[name] = value;
|
||||
}
|
||||
|
||||
if (isFunction(value)) {
|
||||
value = value.call(this.view);
|
||||
}
|
||||
|
||||
return value;
|
||||
};
|
||||
|
||||
/**
|
||||
* A Writer knows how to take a stream of tokens and render them to a
|
||||
* string, given a context. It also maintains a cache of templates to
|
||||
* avoid the need to parse the same template twice.
|
||||
*/
|
||||
function Writer() {
|
||||
this.cache = {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears all cached templates in this writer.
|
||||
*/
|
||||
Writer.prototype.clearCache = function () {
|
||||
this.cache = {};
|
||||
};
|
||||
|
||||
/**
|
||||
* Parses and caches the given `template` and returns the array of tokens
|
||||
* that is generated from the parse.
|
||||
*/
|
||||
Writer.prototype.parse = function (template, tags) {
|
||||
var cache = this.cache;
|
||||
var tokens = cache[template];
|
||||
|
||||
if (tokens == null) {
|
||||
tokens = cache[template] = parseTemplate(template, tags);
|
||||
}
|
||||
|
||||
return tokens;
|
||||
};
|
||||
|
||||
/**
|
||||
* High-level method that is used to render the given `template` with
|
||||
* the given `view`.
|
||||
*
|
||||
* The optional `partials` argument may be an object that contains the
|
||||
* names and templates of partials that are used in the template. It may
|
||||
* also be a function that is used to load partial templates on the fly
|
||||
* that takes a single argument: the name of the partial.
|
||||
*/
|
||||
Writer.prototype.render = function (template, view, partials) {
|
||||
var tokens = this.parse(template);
|
||||
var context = (view instanceof Context) ? view : new Context(view);
|
||||
return this.renderTokens(tokens, context, partials, template);
|
||||
};
|
||||
|
||||
/**
|
||||
* Low-level method that renders the given array of `tokens` using
|
||||
* the given `context` and `partials`.
|
||||
*
|
||||
* Note: The `originalTemplate` is only ever used to extract the portion
|
||||
* of the original template that was contained in a higher-order section.
|
||||
* If the template doesn't use higher-order sections, this argument may
|
||||
* be omitted.
|
||||
*/
|
||||
Writer.prototype.renderTokens = function (tokens, context, partials, originalTemplate) {
|
||||
var buffer = '';
|
||||
|
||||
// This function is used to render an arbitrary template
|
||||
// in the current context by higher-order sections.
|
||||
var self = this;
|
||||
function subRender(template) {
|
||||
return self.render(template, context, partials);
|
||||
}
|
||||
|
||||
var token, value;
|
||||
for (var i = 0, len = tokens.length; i < len; ++i) {
|
||||
token = tokens[i];
|
||||
|
||||
switch (token[0]) {
|
||||
case '#':
|
||||
value = context.lookup(token[1]);
|
||||
if (!value) continue;
|
||||
|
||||
if (isArray(value)) {
|
||||
for (var j = 0, jlen = value.length; j < jlen; ++j) {
|
||||
buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate);
|
||||
}
|
||||
} else if (typeof value === 'object' || typeof value === 'string') {
|
||||
buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate);
|
||||
} else if (isFunction(value)) {
|
||||
if (typeof originalTemplate !== 'string') {
|
||||
throw new Error('Cannot use higher-order sections without the original template');
|
||||
}
|
||||
|
||||
// Extract the portion of the original template that the section contains.
|
||||
value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender);
|
||||
|
||||
if (value != null) buffer += value;
|
||||
} else {
|
||||
buffer += this.renderTokens(token[4], context, partials, originalTemplate);
|
||||
}
|
||||
|
||||
break;
|
||||
case '^':
|
||||
value = context.lookup(token[1]);
|
||||
|
||||
// Use JavaScript's definition of falsy. Include empty arrays.
|
||||
// See https://github.com/janl/mustache.js/issues/186
|
||||
if (!value || (isArray(value) && value.length === 0)) {
|
||||
buffer += this.renderTokens(token[4], context, partials, originalTemplate);
|
||||
}
|
||||
|
||||
break;
|
||||
case '>':
|
||||
if (!partials) continue;
|
||||
value = isFunction(partials) ? partials(token[1]) : partials[token[1]];
|
||||
if (value != null) buffer += this.renderTokens(this.parse(value), context, partials, value);
|
||||
break;
|
||||
case '&':
|
||||
value = context.lookup(token[1]);
|
||||
if (value != null) buffer += value;
|
||||
break;
|
||||
case 'name':
|
||||
value = context.lookup(token[1]);
|
||||
if (value != null) buffer += mustache.escape(value);
|
||||
break;
|
||||
case 'text':
|
||||
buffer += token[1];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return buffer;
|
||||
};
|
||||
|
||||
mustache.name = "mustache.js";
|
||||
mustache.version = "0.8.1";
|
||||
mustache.tags = [ "{{", "}}" ];
|
||||
|
||||
// All high-level mustache.* functions use this writer.
|
||||
var defaultWriter = new Writer();
|
||||
|
||||
/**
|
||||
* Clears all cached templates in the default writer.
|
||||
*/
|
||||
mustache.clearCache = function () {
|
||||
return defaultWriter.clearCache();
|
||||
};
|
||||
|
||||
/**
|
||||
* Parses and caches the given template in the default writer and returns the
|
||||
* array of tokens it contains. Doing this ahead of time avoids the need to
|
||||
* parse templates on the fly as they are rendered.
|
||||
*/
|
||||
mustache.parse = function (template, tags) {
|
||||
return defaultWriter.parse(template, tags);
|
||||
};
|
||||
|
||||
/**
|
||||
* Renders the `template` with the given `view` and `partials` using the
|
||||
* default writer.
|
||||
*/
|
||||
mustache.render = function (template, view, partials) {
|
||||
return defaultWriter.render(template, view, partials);
|
||||
};
|
||||
|
||||
// This is here for backwards compatibility with 0.4.x.
|
||||
mustache.to_html = function (template, view, partials, send) {
|
||||
var result = mustache.render(template, view, partials);
|
||||
|
||||
if (isFunction(send)) {
|
||||
send(result);
|
||||
} else {
|
||||
return result;
|
||||
}
|
||||
};
|
||||
|
||||
// Export the escaping function so that the user may override it.
|
||||
// See https://github.com/janl/mustache.js/issues/244
|
||||
mustache.escape = escapeHtml;
|
||||
|
||||
// Export these mainly for testing, but also for advanced usage.
|
||||
mustache.Scanner = Scanner;
|
||||
mustache.Context = Context;
|
||||
mustache.Writer = Writer;
|
||||
|
||||
}));
|
||||
Reference in New Issue
Block a user