[英]block iterator, embedded ruby giving me a syntax error
原諒noob問題,但我做錯了什么?
<ul>
<% ['red', 'white', 'green'].each do |y| %>
<li><%= "#{y} is a color on the Mexican flag" %></li>
<% end %>
</ul>
我收到以下錯誤:
syntax error, unexpected '<', expecting end-of-input
編輯***這是我的完整代碼:
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>
錯誤出現在<from the
<ul>
線
我們不能在ruby代碼中使用HTML標記。 請閱讀http://apidock.com/ruby/ERB , http://ruby-doc.org/stdlib-2.1.1/libdoc/erb/rdoc/ERB.html
這解釋了如何在Ruby中使用erb模板
這是它的工作原理,
['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
您不能在同一文件中編寫純Ruby代碼和ERB模板。 Ruby代碼應由Ruby解釋,ERB模板應由ERB翻譯。 你可以使用這里的文檔引用模板,使它成為有效的Ruby字符串,然后用ERB解析它。 就像你在前幾行中所做的一樣。
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)
如果您在大多數情況下使用Rails,則無需手動操作ERB模塊。 erb模板應該位於app/views/
文件夾中,而ruby邏輯應該轉到app/models/
folder或app/controllers/
或其他一些庫文件夾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.