首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >块迭代器,嵌入的ruby给我一个语法错误。

块迭代器,嵌入的ruby给我一个语法错误。
EN

Stack Overflow用户
提问于 2014-03-11 07:41:21
回答 2查看 101关注 0票数 0

原谅我的问题,但我做错了什么?

代码语言:javascript
运行
复制
<ul> 
  <% ['red', 'white', 'green'].each do |y| %> 
    <li><%= "#{y} is a color on the Mexican flag" %></li>
  <% end %>
</ul>

我得到以下错误:

代码语言:javascript
运行
复制
syntax error, unexpected '<', expecting end-of-input

编辑*这是我的完整代码:

代码语言:javascript
运行
复制
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>

错误出现在<来自

代码语言:javascript
运行
复制
<ul>

线路

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-03-11 08:03:00

我们不能在红宝石代码中使用HTML标记。请阅读http://apidock.com/ruby/ERBhttp://ruby-doc.org/stdlib-2.1.1/libdoc/erb/rdoc/ERB.html

这说明了如何在Ruby中使用erb模板。

这是它的工作原理,

代码语言:javascript
运行
复制
['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 
票数 1
EN

Stack Overflow用户

发布于 2014-03-11 08:14:36

您不能在同一个文件中编写普通Ruby代码和ERB模板。Ruby代码应由Ruby解释,ERB模板应由ERB翻译。您可以在这里使用文档引用模板,以便它成为有效的Ruby字符串,然后用ERB解析它。就像你在前几行中所做的那样。

代码语言:javascript
运行
复制
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/文件夹或app/controllers/或其他库文件夹中。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22319272

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档