简体   繁体   中英

Using Ruby Variables in JavaScript

I'm new to Ruby so I had a question in regards to using some variables throughout my codebase. I have a variable declared in my Ruby file as follows:

@pages = 350

Now, I know that in HAML, I can simply do: -if @pages = 350 , and in HAML with inline javascript, I can do something like:

:javascript
   console.log("#{@pages}");

However, I am linking an external JavaScript file in my HAML document, and I was wondering if it would be possible to use my Ruby variables in my external JS document? I need some variables in order to build what I am trying to build. Thanks!

Update as per one of the answers:

In my HAML file, I have the following:

:javascript
   printPages(3);

In my external JS file, I have:

$(function() { 
   window.printPages = function(pages) { 
        console.log(pages);
    }
});

I you are loading static javascript files I really would not recommend trying to insert variables into that code.

Instead, think about how you would provide that to your javascript code.


You could send it to that code as an argument.

<script type="text/javascript" src="./my-external-script.js"></script>

:javascript
  runMyExternalFunction(#{@pages})

Or you could add the variable as a data attribute on your page, and your javascript could look for that when it loads.

Haml:

%body data-pages=@pages

JS:

console.log(document.body.dataset.pages) // value of @pages

Update about your javascript:

Using jquery's on page ready event $() for declaring the function is a bad idea. That means that it waits for everything on the page to be compeletely loaded, and then declares the function your page needs.

What you should be doing is setting up all the function that will be needed right away, and then calling those functions when the page is loaded.

They way you have it, the page loads, printPages() is executed (which doesn't exist yet), and then after all that printPages is created and put into the global scope.

So remove the $() from your external script and add it to your HAML instead.

In fact, if your aren't doing anything super fancy with transpiling or bundling, then you can simply declare the function in your external JS file, and it will be available globally. This doesn't work with your code because they way you've declared the function, it would only be available to code within that $() callback.

// js file
function printPages(pages) { 
    console.log(pages);
}

HAML:

$(() => {
  printPages({@pages})
})

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