Tuesday, August 20, 2013

Getting Rails variables into external JavaScript files

It is often convenient to keep JavaScript code in external .js files and pull them into a web page using this HTML command:

<script src="external.js"></script>

In a normal rails .erb or .haml view, you can't use a rails variable value inside the external JavaScript file. The trick is to set the value in an HTML meta tag, then use JavaScript to read the meta tag after the DOM is ready. For example, in the .erb view file, use:

<meta name='railsvariable' content='<%= @railsvar %>' /%>

Then, in the JavaScript file, using the Dojo query function:

var railsvar = query('meta[name="railsvariable"]')[0].content;

In raw JavaScript, it would be this:

var railsvar = document.getElementsByTagName('meta').item(property='railsvariable').getAttribute('content');

No comments:

Post a Comment