Question

Forgive the noob question but what am I doing wrong?

<ul> 
  <% ['red', 'white', 'green'].each do |y| %> 
    <li><%= "#{y} is a color on the Mexican flag" %></li>
  <% end %>
</ul>

I get the following error:

syntax error, unexpected '<', expecting end-of-input

EDIT*** this is my full code:

require 'erb'

x = 42
template = ERB.new "The value of x is: <%= x %>"
puts template.result(binding)


puts "hello world"


<ul>
<% ['red', 'white', 'green'].each do |y| %> 
    <li><%= "#{y} is a color on the Mexican flag" %></li>
<% end %>
</ul>

The error comes on the < from the

<ul>

line

Was it helpful?

Solution

We cant use HTML tag in a ruby code. Please read http://apidock.com/ruby/ERB , http://ruby-doc.org/stdlib-2.1.1/libdoc/erb/rdoc/ERB.html

This explains how to use erb template in Ruby

Here it how it works,

['red', 'white', 'green'].each do |y| 
    temp = ERB.new <<-EOF 
        <li><%= "#{y} is a color on the Mexican flag" %></li>
    EOF
    puts temp.result(binding)
end 

OTHER TIPS

You cannot write plain Ruby code and ERB template in the same file. Ruby code should be interpreted by Ruby, and the ERB template should be translated by ERB. You can use here document to quote the template, so that it becomes valid Ruby string, and then parse it with ERB. Just like what you have done in the previous lines.

require 'erb'

x = 42
template = ERB.new "The value of x is: <%= x %>"
puts template.result(binding)

puts "hello world"

template = ERB.new <<'END_TEMPLATE'
<ul>
<% ['red', 'white', 'green'].each do |y| %> 
    <li><%= "#{y} is a color on the Mexican flag" %></li>
<% end %>
</ul>
END_TEMPLATE
puts template.result(binding)

If you're using Rails, for most of the time, you don't have to manipulate ERB module manually. The erb template should be located in app/views/ folder while the ruby logic should goes to app/models/ folder or app/controllers/, or some other library folder.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top