I'm using escape_javascript to return a partial to the browser via ajax.
Something like:
$("#inject").html("<%=escape_javascript(render :partial =>"feed/index")%>");
Problem is escape_javascript ends up outputing all kinds of wasted space like
\n\n\n\n\n \n
Is there anyway in Rails to escape_javascript more efficiently? No need for \n or long gaps of spaces?
Thanks
There is no standard Rails way to do this. You could just remove it yourself before passing it to escape_javascript like this:
$("#inject").html("<%= escape_javascript((render :partial => 'feed/index').squeeze(" ").gsub(/[\n\t]/,'')) %>");
I'm sure there's a sweet regular expression that would do it better, but this will get pretty close and won't harm your HTML. The gsub will replace newlines and tabs with nothing. The squeeze method will replace multiple occurrences of spaces with just one space. You don't want to remove all spaces because they likely occur intentionally in your HTML.
I'm going to revive this thread since I believe there is a misconception here.
The escape_javascript method, which can also be shortened to j, should not display any escaped line breaks (\n) when used with jQuery's append, prepend, html or functions of the like.
The most likely situation is that your rendered partial "feed/index" has another partial within it that is being escaped as well. This means you are javascript escaping your line breaks twice, which causes them to get interpreted improperly.
Related
I've read in multiple places that as of Rails 3 you no longer have to use html_escape "some string" to actually escape a string in a view and that simply writing <%= "some string" %> would escape the string by default. However, I cannot find this information in the docs. I read through the XSS in the Rails guides section that stated this:
https://guides.rubyonrails.org/security.html#cross-site-scripting-xss
As a second step, it is good practice to escape all output of the application, especially when re-displaying user input, which hasn't been input-filtered (as in the search form example earlier on). Use escapeHTML() (or its alias h()) method to replace the HTML input characters &, ", <, and > by their uninterpreted representations in HTML (&, ", <, and >).
Then I see several blogs that state that it is escaped by default. For example: https://www.netsparker.com/blog/web-security/preventing-xss-ruby-on-rails-web-applications/
https://dzone.com/articles/preventing-cross-site-scripting-vulnerabilities-wh
Found it:
https://guides.rubyonrails.org/3_0_release_notes.html
"7.4.3 Other Changes
You no longer need to call h(string) to escape HTML output, it is on by default in all view templates. If you want the unescaped string, call raw(string)."
escapeHTML() (or its alias h()) are from CGI::escapeHTML, which is a Ruby API implementation. If you aren't using Rails you still have a way to escape HTML. Rails may do some automagical handling of HTML in ERB files for display, and that is what you are probably referring to with html_escape "some string" and <%= "some string" %>. I think you are possibly confusing html_escape which you might need when displaying urls and such that are stored in the DB and you want the ERB processor to not mess it up? I know sometimes, particularly in .js.erb files I need to escape some things to get the result I was expecting. This is different than sanitizing. It seems in your example they are referring to something that you might accept and then redisplay, like a search string. If you put <i>hello</i> into a search box you would want to sanitize the input before passing it to the back end, or if you are using some javascript to filter you might want to escape it both for security reasons and to let it re-display correctly in the search box after you've filtered.
Edit: I was not able to find the answer to your comment in the ri doc either. But I tried:
<%= "<b>hello</b>" %>
<%= h("<b>hello</b>") %>
And got the same result in the browser:
<b>hello</b>
<b>hello</b>
So if you are asking if it is true, then I would say yes.
I'm basically trying to produce jQuery effects based on the data I am coming in with from the server. I've tried multiple methods but its not coming out correctly
:javascript
"#{if #user.nil?}"
$('#test-container').show();
"#{end}"
The contents of #{...} need to be a single expression, and is allowed to go over multiple lines. Inside #{...} you can use literal strings simply by quoting them, and you don’t need quotes around the whole thing.
:javascript
#{if #user.nil?
"$('#test-container').show();"
end}
In this case you can do it as a single line:
:javascript
#{"$('#test-container').show();" if #user.nil?}
In general you want to avoid complex multiline interpolated blocks like in the first example. If necessary you should look at creating helpers to keep your views simple and understandable.
Does this work?
- unless #user
:javascript
$('#test-container').show();
I have a chunk of code provided by Wistia to embed videos into a page. This source is embedable raw html and they include some ampersands in it directly. Of course my w3c validator yells at me all day long and with these in it I'm getting hundreds of errors like:
& did not start a character reference. (& probably should have been escaped as &.)
My view is in HAML so I'm assuming that I needed to escape the sequence, which I happily did with:
:escape
<object width="...
Upon doing this the video no longer loads as it has escaped the entire string with <object width=" ... etc.
How would one properly escape such sequences programmatically vs manually altering the inserted string each time a new update is made in Rails 3.1 with HAML?
You'll probably want to put your HTML into its own partial, then render it into a string and do a String#gsub on it.
Put your Wistia HTML into a partial called something like app/views/shared/_wistia.html
Then create a helper that looks like:
def embed_video(partial)
html = render_to_string(:partial => "shared/#{partial}")
html.gsub '&', '&'
end
And in your HAML, just put = embed_video 'wistia' wherever you want the video to be inserted.
I developing a blog and some really annoying stuff is happening with newline characters (\n). Everything works fine except if I make a post that contains pre tags my newline characters screw up the indentation.
So if I have code that looks like this
<pre>
<code>
some code some code
more code more code
</code>
</pre>
For some reason the newline characters that are saved in the db field with the post are causing whatever is inside the pre tag to be indented by a tab or two.
I have no idea why it's doing it, but if I do something like
string.gsub!(/\n/, "<br />")
The indentation is removed, so I know it has to do with the \n. But then my problem is that there are way too many line breaks and the format is then way off.
So then I tried to capture everything inside the pre tags with a method that looks like this
def remove_newlines(string)
regexp = /<pre>\s?(.*?)\s?<\/pre>/
code = regexp.match(string)
code[1].gsub!(/\n/, "<br />")
end
But I can't get that to work properly.
Anyone know how I can rid of this weird indentation problem, or any pointers on this?
Thanks!
It sounds like your template engine is auto-indenting the contents of the <pre> tags. Browsers render the whitespace inside <pre> tags as it is (and so they should, according to specs). This means that the whitespace at the beginning of each line inside the <pre> added by the template engine in order to make the HTML source more readable is rendered in the actual page as well, unlike whitespace most other places in HTML source.
The solution therefore depends on your templating language.
If you are using HAML:
HAML FAQ: How do I stop Haml from indenting the contents of my pre and textarea tags?
Hope this helps.
I am working on a simple Rails/jQuery HTML templater app which stores a series of pre-designed templates in a database (at the moment I've just saved these as partials to get the basic concept working) and on clicking 'Show code' alongside any one of these template records, a js.erb script should place the corresponding partial within 'pre' tags dynamically via JS on that page so the user can see the raw html code.
At the moment it's working but I get the rendered html coming back and not the raw HTML that I'm looking for. Here's the js:
$("div#template-view").html("<pre><code><%= escape_javascript( render :partial => "core_template") %></code></pre>");
So pray tell, what obvious thing am I missing!? :-)
Thanks
Allan
Use
$("div#template-view").text("...")
instead. This will not parse the code
The pre tag will show source code (or any text) in a reasonable approximation to it's original state, but it won't escape html for you. Unescaped html will always be rendered as html regardless of what tag it happens to be in. By escaped i mean that all the special characters are converted to their escaped versions. The rails method h will do this for you, so if you call h with the results of calling escape_javascript then it should work fine.
$("div#template-view").html("<pre><code><%= h(escape_javascript(render :partial => "core_template")) %></code></pre>");