How to Embed Ruby in JavaScript (Rails + .Html.Erb File)

Inserting ERB with JavaScript

in an .html.erb file, you can use an actionview helper to generate a string like this:

<%= javascript_tag do %>
const foo = '<%= select_tag(:foo, raw("<option>bar</option><option>baz</option>")) %>'
$('#put_it_here').append(foo)
<% end %>

you can use options_for_select too, but I didn't have anything handy to check it, so my example just uses raw options tags.

the resulting output in the browser is:

<script>
//<![CDATA[

const foo = '<select name="foo" id="foo"><option>bish</option><option>bash</option></select>'
$('#put_it_here').append(foo)

//]]>
</script>

and you can use the string 'foo' in your javascript expression to insert it dynamically where you wish, I've used jQuery here.

If you need to use the <select>...</select> html string in an included js file, you can declare it in the .html.erb file and later use it in the included file.

Ruby on Rails Embed Ruby Code in Javascript inside Application Erb File

Change this:

<%= current_user_json %>

To this:

<%= current_user_json.html_safe %>

Heads up that you must ensure your json is properly escaped. For example, if your current_user_json happens to have a field with a quote in it, you must escape that quote. If you don't escape, then what you're doing is a pretty typical attack vector for hackers, so proceed with care.

How to call js and css files inside a html.erb file

You can include the JavaScript in the .html.erb file in the same way you load the text file. The simplest (code wise) solution is doing something along the lines of this:

plan.html.erb

<script>
<%= File.read('some/file.js') %>
</script>

However if you are expecting a <script src="some/file.js"></script> as result you'll have to create your own helper or use an existing one from some light weight web framework. A simple example might be:

lib/html_helpers.rb

require 'builder'

module HtmlHelpers

def javascript_include_tag(path)
Builder::XmlMarkup.new.script('', src: path)
#=> %{<script src="#{html_escaped_path}"></script>}
end

end

plan.html.erb

<% require 'html_helpers' %>
<% include HtmlHelpers %>
<%= javascript_include_tag('some/file.js') %>

Keep in mind that the first solution doesn't escape any HTML characters. Meaning that if your script contains </script> everything following that tag will be interpreted as HTML.

Passing JavaScript value to Ruby in ERB

The appropriate way of achieving this is using ajax in your script.

For instance you can use coffee script and do the something like this.

ABC = ->
variable = document.getElementById('textfield').value
res = $.ajax(
url: '#{method_controller_path}'
method: 'GET'
data:
param: variable
dataType: 'json'
success: (res) ->
res
)

At the end you will have the res object to work with.

Incase you are not using coffee or external script files. You can do this using javascript in the index.html.erb file.

Here is an example for that.

const ABC = function() {
let res;
const variable = document.getElementById('textfield').value;
return res = $.ajax({
url: '#{method_controller_path}',
method: 'GET',
data: {
param: variable
},
dataType: 'json',
success(res) {
return res;
}
});
};

Hope this helps you out. :)

Ruby on Rails - Call both html.erb and js.erb

The controller responds with the format that the request asks for, so, your link asks for HTML, not JS, thus the controller responds with .html.erb. If you add a call, like this:

<%= link_to c.name, show_category_path(category: c.id), :id => "btn-filter#{c.id}", remote: true %>

Your request will ask for JS (because of the remote: true attribute) and the controller will respond with .js.erb.

Include same js file in multiple html.erb files in Rails

No, normally the javascript code is not available in the other views, just in the one where you include it. So you need to include it again.

The exception would be if you have it in a layout file like application.html.erb because this on is rendered in all views.

If you call the javascript package in both partials anyway, then you can also just call it in main, after the if statement. This will be loaded after the partials have been loaded. It might seem weird, to require a piece javascript in a file that doesn't seem to have the html elements that you are using in the JS file, however, the partials are just a way to organise the code in rails. In the end they will be merged into one big html file.

In the comments you said this if statement is nested into another if statement, so maybe you don't need the javascript at all? Paste it at the end of the if statement like so

<% if outer_if_statment %>
<% if some_condition %>
<% render partial: 'first_partial' %>
<% elsif some_other_condition %>
<% render partial: 'second_partial' %>
<% else %>
<% render partial: 'first_partial' %>
<% render partial: 'second_partial' %>
<% end %>
<%= javascript_include_tag 'common' %>
<% else %>
...
<% end %>

This way it will be available in for all partials but not, if the inner if statement is not chosen.

Another thing:
Javascript should be loaded at the end of the html file anyway so that the user doens't have to wait for it to load while he/she doesn't see any html elements. If we put the javascript right in the middle of a hmtl file like this, we're infringing this principle.

Now there is a helper to that:
You can define a second yield in your application.html.erb

 <body>
<%= yield %>
<%= javascript_include_tag 'application' %>
<%= javascript_pack_tag 'application' %>

<%= yield(:after_js) %>
</body>

In the views, you can call it like this:

<%= content_for :after_js do %>
<%= javascript_include_tag 'common' %>
<% end %>

This will make sure, that the JS is loaded at the end of the body and that all other JS code is loaded beforehand (if there are any dependencies).
And, if you still only want to load it depending on the conditions you could repeat the if statement inside the content_for block.

Depending on what your JS script looks like, you can also make sure it only executes, if the necessary HTML element is found on the page. Let's imagine you want to add an event listener on a button.

// common.js
const button = document.querySelector("#red-button")
if (button) {
button.addEventListener(...)
}

How to pass the value to javascript in html.erb rails

You must print it as embedded ruby, and wrap it within quotes:

<% @users.each do |user| %>
<tr>
<td><%= user.name %></td>
<td><%= user.skypeid %></td>
<td><%= link_to 'Show', user_path(user) %></td>
<td>
<div id="SkypeButton_Call_aaa_1">
<script type="text/javascript">
Skype.ui({
"name": "call",
"element": "SkypeButton_Call_aaa_1",
"participants": ['<%= user.skypeid %>']
});
</script>
</div>
</td>
</tr>
<% end %>

Although you could move the script it outside or to another file:

<% @users.each do |user| %>
<tr class="">
<td><%= user.name %></td>
<td><%= user.skypeid %></td>
<td><%= link_to 'Show', user_path(user) %></td>
<td>
<div id="SkypeButton_Call_aaa_1" data-skype="<%= user.skypeid %>"></div>
</td>
</tr>
<% end %>

<script type="text/javascript">
let id = 'SkypeButton_Call_aaa_1'
let user = document.getElementById(id).dataset
Skype.ui({
'name': 'call', 'element': id, 'participants': [user.skype]
})
</script>


Related Topics



Leave a reply



Submit