Your attempt is almost correct, you don't need to escape the double quotes inside the ruby code though:
var v2="<%= "Our funding ask is #{@startup.funding_ask_text}." if @startup.try(:funding_ask_text) %>";
Question
I have the ruby code:
<%= "hello #{@namevar}" if condition %>
I can include ruby snippet in JS in the following way-
<script>
var v1="<%= @user.name %>"
</script>
But can't embed the previous code in JavaScript.
I have tried the following:
var v2="<%= \"hello #{@namevar}\" if condition %>";
But didn't work.
Thanx.
Solution
Your attempt is almost correct, you don't need to escape the double quotes inside the ruby code though:
var v2="<%= "Our funding ask is #{@startup.funding_ask_text}." if @startup.try(:funding_ask_text) %>";
OTHER TIPS
Asset Pipeline
You can't include ruby code in your asset pipeline
If you want to include "naked" ruby, you'll have to use .js.erb
and put the file in your views
directory. The reason for this is because the asset pipeline can be precompiled
, which will render the Ruby code useless
Vars
If you want to use rails-based data in your JS, you'll have to first render the data in your views, and then call it from JS (like Bachan's answer)
You can use the Gon
gem for this
In your layout add a hidden_field
<%= hidden_field_tag 'user_name', @user.name%>
And in script
var v1 = $('#user_name').val()