epsilones
epsilones

Reputation: 11609

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 ?

Upvotes: 4

Views: 107

Answers (4)

epsilones
epsilones

Reputation: 11609

In fact, I got it, one of the right thing to do is :

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

Upvotes: 2

user2261892
user2261892

Reputation: 188

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")}");"

Upvotes: 3

Ian
Ian

Reputation: 50913

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 :)

Upvotes: 3

yitwail
yitwail

Reputation: 2009

The obvious thing to do is edit layouts/show_some_file & remove white space. It's not really whitespace that's the problem, but carriage returns. Javascript doesn't like multi-line strings. If I knew Ruby, I could probably write a regex that gets rid off stuff like "\r\n", which is carriage return line feed in PHP/C syntax.

Upvotes: -1

Related Questions