1

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.

2
  • What do you want to do? Assign the string to a variable depending on a condition?CommentedMar 6, 2014 at 9:19
  • I want this <%= "hello #{@namevar}" if condition %> to get into a JS variableCommentedMar 6, 2014 at 9:19

3 Answers 3

3

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) %>"; 
1
  • Thanx. this worked. I didn't event expect it to work according to conventions. Thanx.CommentedMar 6, 2014 at 9:53
1

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

3
  • var v1="<%= @user.name %>" wasn't a problem at all. So what do u want to say?CommentedMar 6, 2014 at 9:58
  • I don't want to "say" anything - I was trying to give you some idea as to how to include vars in your asset JS. Including naked ruby code in your asset pipeline is bad practice & will lead to problems in futureCommentedMar 6, 2014 at 10:01
  • 1
    Ok. thanx for the elaboration. +1CommentedMar 6, 2014 at 17:31
0

In your layout add a hidden_field

<%= hidden_field_tag 'user_name', @user.name%> 

And in script

var v1 = $('#user_name').val() 
1
  • This should be simple. But you r giving such a solution for which I need an extra dom element!!! This definitely is not the solution.CommentedMar 6, 2014 at 9:25

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.