CleanEcoTemplate for Sprockets in Rails app
|
# Put this file in lib/ |
|
|
|
require 'sprockets/eco_template' |
|
|
|
class CleanEcoTemplate < Sprockets::EcoTemplate |
|
FROM = " (function() {" |
|
TO = "}).call(__obj);" |
|
|
|
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 |
|
# Must include eco-helpers.js before eco files |
|
|
|
(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); |
|
# Put this file in config/initializers |
|
|
|
require 'clean_eco_template' |
|
|
|
Rails.application.assets.register_engine '.eco', CleanEcoTemplate |