简体   繁体   中英

Using Javascript in Ruby

In my Rails project, I have a file /app/assets/javascripts/bootstrap-tab.js which allows me to use tabs in my Rails project, which uses Twitter Bootstrap HTML.

I also have a file /app/views/folder1/show.html.erb that uses the tabs:

<h3>Tabs</h3><br>
<ul class="nav nav-tabs">
    <li class="active"><a href="#tab1" data-toggle="tab">Tab1</a></li>
    <li><a href="#tab2" data-toggle="tab">Tab2</a></li>
</ul>     
<div class="tab-content">
    <div class="tab-pane active" id="tab1">
        <div class="well">
        Text1
        </br>
        <%= @myobject.name %>
        </div>
    </div>
    <div class="tab-pane" id="tab2">
        <div class="well">
        Text2
        </div>
    </div>
</div>

However I need it to know where the javascript file is. What is the ruby way to do this? Would I still just put something like

<script src="/assets/javascriptss/bootstrap-tab.js"></script>

into the show.html.erb ? And if so, what path would I put?

There is no need for you to link to the Javascript file. Rails does this automatically and includes it in the Assets pipeline, which then makes it available to all your app. Read this guide: http://guides.rubyonrails.org/asset_pipeline.html . It discusses how to the asset pipeline works and its advantages.

If for some reason (I can't think of any), the javascript file is not being included in the asset pipeline even though it is in the appropriate location (as it seems to be), maybe you should explicitly include it in your application.js file.

If you want the js file to be added to only 1 view and not other then you could use something like this

<%= javascript_include_tag "bootstrap-tab" %>

For more read 3.1.2 http://guides.rubyonrails.org/layouts_and_rendering.html#asset-tag-helpers

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