Strings passed from controller to view in Rails arrive empty

I am trying to pass a string to my view from controller like this:

controller:

def index
    @str = 'foo'
end

view:

String: <% @str %>

The variable itself seems to arrive because I get no error. However, it arrives empty (only "String" is in html, nothing else). And it seems to work great with other built-in types, e.g. Time. What am I missing here? I use Ruby 2.2.1 and Rails 4.

Upvotes: 0

Views: 55

Answers (5)

Dan
Dan

Reputation: 536

As the other users have pointed out, you need to use <%=

The = is an ERB flag to so export the result of the code inside of the tags and put it into the DOM.

If you want to put some logic into your page that you don't want to evaluate, you leave the = out.

<% if user_wants_to_see_output? %>
    <%= "User will see this" %>
<% end %>

Upvotes: 0

Kyle H
Kyle H

Reputation: 3295

As others have said, you need to use

<%= @str %>

I'll give you an explanation as well - you use <% %> for when you need to run some Ruby code that you don't want displayed to the screen. For example, you might have conditional logic like

<% if user_signed_in? %>
    <%= @welcome_string %>
<% end %>

Use <%= %> when you want to output, drop the '=' for conditional logic or anything that doesn't need to display.

Upvotes: 2

Sarwan Kumar
Sarwan Kumar

Reputation: 1311

In view user following code:

String: <%= @str %>

Upvotes: 1

djaszczurowski
djaszczurowski

Reputation: 4515

in your view

String: <%= @str %>

Upvotes: 1

zwippie
zwippie

Reputation: 15515

In your view, use:

<%= @str %>

Upvotes: 0

Related Questions