How do import a Javascript file into a Haml view?

2020-08-09 10:02发布

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?

3条回答
够拽才男人
2楼-- · 2020-08-09 10:53

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

查看更多
贪生不怕死
3楼-- · 2020-08-09 10:54

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"
查看更多
贪生不怕死
4楼-- · 2020-08-09 10:59

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']
查看更多
登录 后发表回答