Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Include Tag Best Practice in a Rails Application

Say I need to call a javascript file in the <head> of an ERb template. My instinct is to do the usual:

<head> <%= javascript_include_tag :defaults %> <!-- For example --> </head> 

in my application's layout. The problem of course becoming that these javascript files are loaded into every page in my application, regardless of whether or not they are needed for the page being viewed.

So what I'm wondering is if there's a good way of loading a javascript into the the headers of, for example, all ERb templates found only in a specific directory.

like image 991
btw Avatar asked Dec 23 '08 21:12

btw


1 Answers

I would use content_for.

For instance, specify the place to insert it in the application layout:

<head> <title>Merry Christmas!</title> <%= yield(:head) -%> </head> 

And send it there from a view:

<%- content_for(:head) do -%> <%= javascript_include_tag :defaults -%> <%- end -%> 
like image 66
maurycy Avatar answered Sep 22 '22 05:09

maurycy