简体   繁体   中英

Rails ERB Contains Javascript

I'm new to Rails and I encounter a problem that I need to put some Javascript into the ERB file. For example,

<script>
    function init() {
        ....
    }
</script>

<% @list.each do |l| %>
   ....
<% end %>

In the template, I have another script to check if function "init()" is exists it will execute after the page finish loading.

When I try it on testing server, the init() cannot be execute. I checked the page source from Web browser the "<script> ... </script>" portion is missing. If I reload the page by click the reload button on Web browser, the portion appear again.

I have try to change something, such as class of the object in HTML, it can update correctly after the ERB file saved but only the javascript cannot be loaded when the page first loading and need to click reload page from browser.

I would like to know is it the cache problem of Rails or anything I get wrong? I'm currently use Rails 4.2.1 on Mac.

Thank you!

If you only need to transport some variables from erb to javascript, you could use hidden fields or attributes on the special tags on that page. So I am sure, you do not really need to use a script tag in erb file, unless you have to include some third party javascript.

I am pretty sure your problem appears because you are using the automatically integrated turbolinks.

Turbolinks will evaluate any script tags in pages it visits, if those tags do not have a type or if the type is text/javascript. All other script tags will be ignored.

From: https://github.com/rails/turbolinks

You could remove them from Gemfile, bundle and try again, to falsify my assumption - or just include the type to the script tag.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM