Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java script failing because of white spaces caracters

I have in my views some code as 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 basic divs

In my browser, I get

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

On hover, I get in my chrome console SyntaxError: Unexpected token ILLEGAL. I deleted my white spaces in my console, and it worked. But how to clean the white spaces in my ruby rendering ?

like image 462
epsilones Avatar asked Mar 23 '23 11:03

epsilones


2 Answers

I am not entirely certain it will help, but you probably should use the "<%= render ... %>" variant rather than the #{}

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

If using HAML, substitute the ERB for however the markup is written there.

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

like image 176
user2261892 Avatar answered Apr 24 '23 18:04

user2261892


Since the result of your {#render} is HTML, and although you might use it once, it might make more sense to store it in HTML, and retrieve it with JavaScript. Mimicking templating, here's 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 kind of acts like a template. You use a script tag, but you set its type to something that doesn't cause it to be executed. Since script tags are never visible on a page, you would never have visual problems...unlike doing this inside of a div...the HTML is then "separate" from the rest of the page.

I'm sure there's a better solution using Ruby, but if you're outputting a partial view to JavaScript code, I'd have to ask why. It makes more sense to me to put in a "template". I understand this doesn't directly answer your immediate question, but it's an alternative :)

like image 29
Ian Avatar answered Apr 24 '23 18:04

Ian