Using Ruby variable in Javascript (In App View)
Assuming the script tag you mentioned is in a html erb view you can just use this:
<script type="text/javascript" charset="utf-8">
var json = <%= @json || 'null' %>;
</script>
How to pass Ruby variables to a JavaScript function in a Rails view?
A few options:
escape_javascript
Alias: j
.
Works only on strings.
Escapes characters that can have special meanings in Javascript strings,
like backslash escapes, into a format suitable to put inside Javascript string literal quotes.
Maintains html_safe
status of input,
so needs html_safe
otherwise special HTML chars like <
would get escaped into <
.
<% a = "\\n<" %>
<%= javascript_tag do %>
'<%= j(a) %>' === '\\n<'
'<%= j(a).html_safe %>' === '\\n<'
<% end %>
to_json + html_safe
As mentioned by Vyacheslav, go upvote him.
Works because JSON is almost a subset of Javascript object literal notation.
Works not only on hash objects, but also on strings, arrays and integers which are
converted to JSON fragments of the corresponding data type.
<% data = { key1: 'val1', key2: 'val2' } %>
<%= javascript_tag do %>
var data = <%= data.to_json.html_safe %>
data.key1 === 'val1'
data.key2 === 'val2'
<% end %>
data- attributes
Add values to attributes, retrieve them with Javascript DOM operations.
Better with the content_tag
helper:
<%= content_tag 'div', '', id: 'data', data: {key1: 'val1', key2: 'val2'} %>
<%= javascript_tag do %>
$('#data').data('key1') === 'val1'
$('#data').data('key2') === 'val2'
<% end %>
Sometimes called "unobtrusive Javascript".
gon
Library specialized for the job: https://github.com/gazay/gon
Probably the most robust solution.
Gemfile:
gem 'gon'
Controller:
gon.key1 = 'val1'
gon.key2 = 'val2'
Layout app/views/layouts/application.html.erb
:
<html>
<head>
<meta charset="utf-8"/>
<%= include_gon %>
View:
<%= javascript_tag do %>
gon.key1 === 'val1'
gon.key2 === 'val2'
<% end %>
See also
- Injecting variable values into javascript and HAML in RoR
How can I use a Ruby variable in an inline JavaScript in haml?
You can use the simple "#{}" interpolation tags to use ruby variables with HAML.
Your code:
:javascript
alert(<%=raw @status %>)
Possible Solution:
:javascript
alert("#{@status}")
How to pass a variable to javascript in Rails 6 app
It's quite a common pattern in Rails applications to pass atrributes via data attributes.
In your view template you'd interpolate the user ID:
<div id="calendar" data-user-id="<%= @user.id %>">
</div>
And in your JavaScript you'd read the user ID via the dataset
:
var calendarEl = document.getElementById('calendar');
var userId = calendarEl.dataset.userId;
How to pass a javascript variable into a erb code in a js view?
As far as i know there is no way to do it directly and the reason is fairly simple too, html is executed at the server side and javascript is a client side language which means its executed in your local browser, thats why if you even try to pass a variable between the two you'll have to make a request to the server,
However this problem is tackled by calling an AJAX request, this AJAX request does the same thing as sending a new request to the server however it does that without refreshing or reloading the page to it gives the users the illusion that no request was made.
a guy asks a similar question Here
and you can learn more about AJAX Here on MDN:
use javascript variable inside ruby code
Ce ne pas possible, mon ami.
As mentioned in the comments, Ruby is server; javascript is client. This means one of two things:
- build the javascript at runtime (not recommended)
- send the ajax / javascript value to the server (via Ajax)
To get this working properly, you'll need to send the request through ajax:
#app/assets/javascripts/application.js
$(document).on("change", "#some_id", function(e) {
$.get("forms/update", {index: $(this).val(), value: $(this).attr('id').to_i});
});
This would need to be addressed by the appropriate route & controller action:
#config/routes.rb
get "color_form", to: "application#color_form"
#app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
respond_to :js, :html
def color_form
@id = params[:id]
@value = params[:value]
end
end
#app/views/application/color_form.js.erb
$('option_value_0').html('<%=j render partial: 'color_form', locals: { index: @index, id: @value } %>')
--
Yes, it's long-winded, but it's the right way.
If you wanted to shortcut, you'd be able to preload the color_form
partial, and then use the javascript functionality to change the id
or value
params. I can write about this if you want.
Preload
If you wanted to do this without ajax, the standard way (this includes modals
, too) is to append the partial to your page and "hide" it.
This way, your JS has the actual HTML code to either show, or append to other parts of the page:
#view
<div class="hidden">
<%= render partial: 'color_form', locals: { f: f, index: "x", id: "y" } %>
</div>
#app/assets/javascripts/application.js
$(document).on("change", "#some_id", function(e) {
$partial = $(".hidden").html();
$partial.find("#id").html($(this).attr('id').to_i);
$partial.find("#index").html($(this).val());
$('option_value_0').html($partial);
});
Related Topics
Get Computed Font Size For Dom Element in Js
Does .Css() Automatically Add Vendor Prefixes
How to Include CSS and Jquery in My Wordpress Plugin
What Is the (Function() { } )() Construct in JavaScript
Jquery - How to Determine If a Div Changes Its Height or Any CSS Attribute
How to Stretch Images With No Antialiasing
Styling ≪Input Type="File"≫
Using Async/Await With a Foreach Loop
What Is the Most Efficient Way to Deep Clone an Object in JavaScript
How to Format a Date in JavaScript
Force Link to Open in Mobile Safari from a Web App With JavaScript
How to Run Untrusted Code Serverside
Use a Content Script to Access the Page Context Variables and Functions
How to Display JavaScript Variables in a HTML Page Without Document.Write