Created
March 15, 2012 11:07
-
-
Save doitian/2043682 to your computer and use it in GitHub Desktop.
CleanEcoTemplate for Sprockets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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, '&') | |
.replace(/</g, '<') | |
.replace(/>/g, '>') | |
.replace(/"/g, '"'); | |
}, | |
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See this fork to setup it in Rails: https://gist.github.com/2360781