Use jQuery to append yield statement to application.html.erb's body?
I'm working on a rails app and would like to hide away some code a bit more thoroughly. At the moment my app开发者_开发问答lication.html.erb just has a <%= yield %> statement in the and I'd like to move that creation to jQuery. I have tried putting this into my application.js:
jQuery(function($) {
$('<div id="wrapper"><%= escape_javascript(yield) %></div>').appendTo('body');
});
But it doesn't work, I'm guessing that's due to the fact that it isn't an erb file so doesn't parse any ruby. Is there any way to get this sort of functionality on load?
Cheers, Steve
Well I sorted it out. Thanks for the replies but I'd like to clarify: You can actually utilise ERB from client-side js, I use it regularly with the render() method. E.g.
$('#myDiv').html("<%= escape_javascript(render( :partial => 'profile' )) %>");
This works nicely. My goal was to mask the html rendered by the the ERB file from the standard right-click->view source. I'm aware that they can still use a DOM inspector to see it all. I implemented this by having that standard application.html.erb with the <%= yield %> statement, however I modified my next action method (show) to render javascript back, I created my show.js.erb with jQuery where I then append the rest of my page to the body tag dynamically using a partial.
The <%= yield %>
stuff is processed on the server side before the result is sent to the browser, you can't produce ERB from your client-side JS and expect it to work.
Your only alternative for that sort of interaction (not that I'm recommending this) would be to have your onload
call an AJAX method on the server, which sent through some part of the document, which your JS could then render to the browser.
Where are you using your javascript code? are you using an external file? the yield statement only works when you use the code on the same page, it does not work on external file
From what you have said, it seems that you are writing the js code in application.js. This will not work. You need to write it in the same file as the HTML where yield is present.
Try writing your code in layout.
精彩评论