Skip to content
This repository


Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Ruby lib that compiles Mustache templates into pure Javascript

branch: master

Fetching latest commit…


Cannot retrieve the latest commit at this time

Octocat-spinner-32 lib
Octocat-spinner-32 test
Octocat-spinner-32 .gitignore
Octocat-spinner-32 .gitmodules
Octocat-spinner-32 .travis.yml
Octocat-spinner-32 Gemfile
Octocat-spinner-32 LICENSE
Octocat-spinner-32 Rakefile
Octocat-spinner-32 mustache-trimmer.gemspec

Mustache Trimmer - Cleanly shaves your mustache into pure JS

Mustache Trimmer is a Ruby library that compiles Mustache templates into pure Javascript functions.


gem install mustache-trimmer


require 'mustache/js'
Mustache.to_javascript("Hello {{planet}}")

Compiled JS function:

function (obj) {
  var out, l1, stack, fetch, escape, isFunction;
  out = [];
  stack = [];
  fetch = function fetch(key) {
    var i, v;
    for (i = stack.length - 1; i >= 0; i -= 1) {
      v = stack[i][key];
      if (v) {
        return v;
  escape = function escape(value) {
    return ('' + value)
      .replace(/&/g, '&')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;');
  isFunction = function isFunction(obj) {
    return !!(obj && obj.constructor && && obj.apply);
  out.push("Hello ");
  l1 = fetch("planet");
  if (isFunction(l1)) {
    l1 = l1();
  return out.join("");


The compiler is not fully mustache-spec compliant. All of the modules are supported except for the optional lambda section. This module requires a mustache parser to be present at runtime.

Instead of lambdas being passed the raw text of a section, a closure is passed as the first argument. Simply call the function to render the section.

  Some expensive stuff.

cacheByUserId: function(section) {
  var key, value;
  key = "user:#{id}";
  if (value = cache[key]) {
    return value;
  } else {
    value = section();
    cache[key] = value;
    return value;

Pro Tip

Use the Google Closure Compiler. Its really good at inlining the template helper functions.

window.hello=function(a){var b,c;b=[];c=[];c.push(a);b.push("Hello ");if((a=function(f){var d,e;for(d=c.length-1;d>=0;d-=1)if(e=c[d][f])return e}("planet"))&&a.constructor&&;b.push((""+a).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"));return b.join("")};


Copyright (c) 2011 Joshua Peek.

Released under the MIT license. See LICENSE for details.

Something went wrong with that request. Please try again.