Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including inline javascript using content_for in rails

Tags:

I am using content_for and yeild to inject javascript files into the bottom of my layout but am wondering what the best practice is for including inline javascript. Specifically I'm wondering where the put the script type declaration:

<% content_for :javascript do %>    <script type="text/javascript"> ... </script> <% end %> 

or

<% content_for :javascript do %> ... <% end %>   <script type="text/javascript">     <%= yield :javascript %>   </script> <% end %> 

I am using the first option now and wondering if it is bad to include multiple

...

declarations within one view. Sometimes I have partials that lead to this.

like image 660
TenJack Avatar asked Mar 17 '10 17:03

TenJack


People also ask

HOW include JavaScript in HAML?

To include JavaScript directly in a Haml view, use the nifty :javascript filter. Haml sees the contents as JavaScript and wraps them in a script tag when rendered as HTML. :javascript alert('foo'); The script tag will be output exactly where you put it in the view.

Can you do inline JavaScript?

Inline JavaScript can be achieved by using Script tag inside the body of the HTML, and instead of specifying the source(src=”…”) of the JavaScript file in the Script tag, we have to write all the JavaScript code inside the Script tag.


1 Answers

I much prefer to have the layout's yield look like this:

<html>   <!-- other stuff -->   <body>    <!-- other stuff  -->    <%= yield :javascript %>   </body> </html> 

Then in a view you can write:

<% content_for :javascript do %>   <script type='text/javascript'>     function doMagic() {       //Mind-blowing awesome code here     }   </script>  <% end %>  <!-- More view Code -->  <%= render :partial => "sub_view_with_javascript" %> 

And in the partial _sub_view_with_javascript.html.erb you can also write:

<% content_for :javascript do %>   <script type='text/javascript'>      function DoMoreMaths() {        return 3+3;      }    </script> <% end %> 

My reasoning for this approach is that the yield and content_for are in different files. It is not DRY to put the script tag in for every content_for but it allows the syntax highlighter to recognize the change in language in each file and helps me there.

If you have multiple content_for calls in a single file to the same symbol (in our case, :javascript) I would consider consolidating them all to the top one, but it's perfect for use with partials.

And HTML is perfectly happy to have as many script blocks as you would like. The only possible gotcha is when working with the code in developer tools like firebug, it takes a little more time to find the right script block for your function. This only happens for me when I need to set a javascript breakpoint to debug.

like image 88
Tilendor Avatar answered Sep 20 '22 05:09

Tilendor