Home > Mobile >  Calling a JS script from inside html.erb Rails 5
Calling a JS script from inside html.erb Rails 5

Time:09-25

I have a Rails 5 app and in index.html.erb I want to call a JS script.

Right I'm using a CDN and it works fine but I want download the two files cookieconsent.js and cookieconsent.css and use them locally.

<script src="https://cdn.jsdelivr.net/gh/orestbida/[email protected]/dist/cookieconsent.js"></script>
  <script>
      var cookieconsent = initCookieConsent();

      cookieconsent.run({
          current_lang : 'en',
          theme_css : 'https://cdn.jsdelivr.net/gh/orestbida/[email protected]/dist/cookieconsent.css',

          languages : {
              en : {
                  consent_modal : {
                      title :  "I use cookies",

                      primary_btn: {
                          text: 'Accept',
                          role: 'accept_all'  //'accept_selected' or 'accept_all'
                      },
                      secondary_btn: {
                          text : 'Reject',
                          role : 'accept_necessary'   //'settings' or 'accept_necessary'
                      }
                  }
              }
          }
      });
  </script>

The problem that I have is that no matter where I put the files the app is not finding them. Originally I put them in app/assets/javascripts/cookieconsent.js and in app/assets/stylesheets/cookieconsent.css and then use it like:

<script src="app/assets/javascripts/cookieconsent.js"></script>
  <script>
      var cookieconsent = initCookieConsent();

      cookieconsent.run({
          current_lang : 'en',
          theme_css : 'app/assets/stylesheets/cookieconsent.css',

          languages : {
              en : {
                  consent_modal : {
                      title :  "I use cookies",

                      primary_btn: {
                          text: 'Accept',
                          role: 'accept_all'  //'accept_selected' or 'accept_all'
                      },
                      secondary_btn: {
                          text : 'Reject',
                          role : 'accept_necessary'   //'settings' or 'accept_necessary'
                      }
                  }
              }
          }
      });
  </script>

But it doesn't found any of the files. Where should I put them? Do I need to configure something else?

CodePudding user response:

Without seeing your application.js file, I'd do the following:

Drop the first line from your view template:

<script src="app/assets/javascripts/cookieconsent.js"></script>

Then be sure to "require" it in app/assets/javascripts/application.js.

//= require cookieconsent

Third, replace the hard coded path to cookieconsent.css with <%= asset_path('cookieconsent.css') %>

Once that is done, you can place the JavaScript snippet anywhere you'd like and you should not get any console errors.

  • Related