How do import a Javascript file into a Haml view?

2020-08-09 10:44发布

问题:

I want to include some Javascript functionality in a Haml view, but I don't want it inserted into every view. Do I have to put the Javascript file in public/javascripts or can I put it in app/assets/javascripts to keep it hidden from user, and still reference from within the haml view file?

How would you do both these options if they are possible?

回答1:

You should just use

!!!
%html
  %head
    = javascript_include_tag "my_js_file"

if it's specific to one place, you should use content_for

!!!
%html
  %head
    = yield(:javascripts)

And then in your view

- content_for :javascripts do
  = javascript_include_tag "my_js_file"


回答2:

Include Directly

If you want the javascript included directly into the haml, you can use :javascript

:javascript
  $(function() { alert("js inside haml"); }

You can put this into a partial and then just render the partial to keep your views clean.

Reference It

If you want to just reference javascript and have the browser pull it in, you should use javascript_include_tag like always. Here, you'll need to make the javascript file a manifest, instead of requiring it into the application.js manifest. Remember to add the manifest to config.assets.precompile in your application.rb, according to http://guides.rubyonrails.org/asset_pipeline.html

(in your haml):

= javascript_include_tag 'somefile'

(in config/application.rb):

config.assets.precompile += ['somefile.js']


回答3:

If your javascript is small and dealy simple, I would suggest include javascript directly in the HAML:

:javascript
  alert('hi hi!')

Otherwise you should use asset pipeline. It makes sure that your javascripts are pre-processed, compressed and minified. It also helps to keep your javascripts well organized (e.g. separation between your scripts and vendor scripts) and easily testable (with testing frameworks like jasmine/jasminerice/evergreen). If you are new to asset pipeline, here is a good read =)