Java script crashes due to spaces

I have in my view some code like this

$(".someclass").hover(function(){ $(this).append("#{render "layouts/show_some_file", title: "some_file"}"); }); 

The show_some_file.html.haml file consists of two nested base divs

In my browser I get

 $(".someclass").hover(function(){ $(this).append("<div> <div>some text</div> </div> "); }); 

In hover mode, I got to the chrome SyntaxError: Unexpected token ILLEGAL . I removed my white spaces in the console and it worked. But how do I clear the gaps in my ruby ​​rendering?

+4
source share
4 answers

I'm not quite sure this will help, but you should probably use the option "<%= render ... %>" and not #{}

And since this is for javascript, the correct way would be "<%= escape_javascript(render ...) %>"

If you use HAML, replace ERB, but the inscription is written there.

Edit: maybe != "$(this).append("#{escape_javascript(render "layouts/show_some_file", title: "some_file")}");"

+3
source

Since the result of your {#render} is HTML, and although you can use it once, it might make sense to store it in HTML and retrieve it using JavaScript. Imitating patterns, here is an example of what I mean:

 <script id="my_render" type="text/template"> #{render "layouts/show_some_file", title: "some_file"} </script> <script type="text/javascript"> $(document).ready(function () { var render_content = $("#my_render").html(); $(".someclass").hover(function () { $(this).append(render_content); }); }); </script> 

It looks like a template. You use the script tag, but you set its type to something that does not cause its execution. Since script tags never appear on the page, you will never have problems with the image ... unlike inside the div ... the HTML is then "separated" from the rest of the page.

I'm sure there is a better solution using Ruby, but if you expose a partial view of JavaScript code, I need to ask why. It makes more sense to me to put a "template". I understand that this does not directly answer your immediate question, but this is an alternative :)

+3
source

In fact, I realized what needs to be done:

 $("someclass").hover(function(){ $(this).append("#{escape_javascript render "layouts/show_some_file", title: "some title"}"); }); 
+2
source

The obvious thing is to edit the layouts / show _some_file and remove the white space. It is not true that the problem is, but the carriage return. Javascript does not like multiline strings. If I knew Ruby, I could probably write a regular expression that will get rid of things like "\ r \ n", which is the return line feed channel in PHP / C syntax.

-1
source

Source: https://habr.com/ru/post/1487300/


All Articles