Skip to content

Instantly share code, notes, and snippets.

@doitian
Created March 15, 2012 11:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save doitian/2043682 to your computer and use it in GitHub Desktop.
Save doitian/2043682 to your computer and use it in GitHub Desktop.
CleanEcoTemplate for Sprockets
require 'sprockets/eco_template'
# Must include eco-helpers.js before eco files
#
# include this file, and add
#
# Sprockets::CleanEcoTemplate.javascripts_dir
#
# to assets paths
#
# Then register it to handle eco files:
#
# sprockets.register_engine '.eco', ::Sprockets::CleanEcoTemplate
#
module Sprockets
class CleanEcoTemplate < EcoTemplate
FROM = " (function() {"
TO = "}).call(__obj);"
def javascripts_dir
File.expand_path('..', __FILE__)
end
def evaluate(scope, locals, &block)
content = Eco.compile(data)
from = content.index(FROM)
to = content.rindex(TO)
content = content[from...to] + TO
<<-JS
function(__obj) {
if (!__obj) __obj = {};
var __helpers = window.ecoHelpers;
var __out = [];
var __sanitize = __helpers.sanitize;
var __capture = __helpers.captureFor(__obj, __out);
var __rememberSafe = __obj.safe;
var __rememberEscape = __obj.escape;
__obj.safe = __helpers.safe;
__obj.escape = __helpers.escape;
#{content}
__obj.safe = __rememberSafe;
__obj.escape = __rememberEscape;
return __out.join('');
};
JS
end
end
end
(function(global) {
var ecoHelpers = {
sanitize: function(value) {
if (value && value.ecoSafe) {
return value;
} else if (typeof value !== 'undefined' && value != null) {
return ecoHelpers.escape(value);
} else {
return '';
}
},
safe: function(value) {
if (value && value.ecoSafe) {
return value;
} else {
if (!(typeof value !== 'undefined' && value != null)) value = '';
var result = new String(value);
result.ecoSafe = true;
return result;
}
},
escape: function(value) {
return ('' + value)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
},
captureFor: function(obj, out) {
return (function(callback) {
var length = out.length;
callback.call(obj);
return ecoHelpers.safe(out.splice(length, out.length - length).join(''));
});
}
};
global.ecoHelpers = ecoHelpers;
})(window);
@doitian
Copy link
Author

doitian commented Apr 15, 2012

See this fork to setup it in Rails: https://gist.github.com/2360781

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment