unescaping javascript in rails .rb file / returning js in ruby methods
I have the following js (in a string literal) returned in one of my plugin's 开发者_开发问答methods. So when I call the method it puts this in my view. The problem is on the website, all the <, ", ', >
etc are escaped into <, "
and whatnot. How can I do this? I've tried various ways but none seem to work :/ I think this plugin may be kind of old so this was possible in earlier versions of Rails...
%Q{<script type="text/javascript">
$(function() {
$('#{table_dom_id}').dataTable({
"oLanguage": {
"sSearch": "#{search_label}",
#{"'sZeroRecords': '#{no_records_message}'," if no_records_message}
"sProcessing": '#{processing}'
},
"sPaginationType": "full_numbers",
"iDisplayLength": #{per_page},
"bProcessing": true,
"bServerSide": #{server_side},
"bLengthChange": false,
"bStateSave": #{persist_state},
"bFilter": #{search},
"bAutoWidth": #{auto_width},
#{"'aaSorting': [#{sort_by}]," if sort_by}
#{"'sAjaxSource': '#{ajax_source}'," if ajax_source}
"aoColumns": [
#{formatted_columns(columns)}
],
#{"'fnRowCallback': function( nRow, aData, iDisplayIndex ) { #{row_callback} }," if row_callback}
"fnServerData": function ( sSource, aoData, fnCallback ) {
aoData.push( #{additional_data_string} );
$.getJSON( sSource, aoData, function (json) {
fnCallback(json);
} );
}
})#{append};
});
</script>}
Any help is appreciated, thanks!
This gets asked pretty often. You need to tell Rails not to escape the string one of two ways:
<%= 'string'.html_safe %>
<%= raw 'string' %>
The first is preferred in most cases since it's more flexible. You can, for instance, mark the string as HTML-Safe when it is defined, then if something modifies it it'll automatically be marked as unsafe. This is good to avoid accidentally opening yourself up to an exploit.
However, it would be a better idea to move that code into a view of some sort. You should avoid having output in your methods. In the case of helpers, limited output code is best (usually just snippets).
Rails automatically escapes html to prevent from XSS attacks. You've got two options:
# Provided that my_escaped_string is what you want to display
<%= my_escaped_string.html_safe %>
<%= raw my_escaped_string %>
You can also use html_safe
in any method as well.
精彩评论