ruby-on-rails - 捕获 Rails View block 时的差异

标签 ruby-on-rails ruby-on-rails-5 actionview

我有一个包含两个块的 ERB View :

<%= test_h1 do %>
  <%= 'test1' %>
<% end -%>

<%= test_h2 do %>
  <%= 'test2' %>
<% end -%>

哪里test_h1test_h2是类似的助手,但一个是在助手文件中定义的,而另一个是通过 helper_method 定义的。在 Controller 中:
module TestHelper
  def test_h1(&block)
    link_to '/url' do
      capture(&block)
    end
  end
end

class TestController < ApplicationController
  helper_method :test_h2

  def test_h2(&block)
    helpers.link_to '/url' do
      helpers.capture(&block)
    end
  end
end
test_h1产生预期结果和 test_h2首先呈现内部模板块:
<a href="/url">test1</a>

test2<a href="/url"></a>

为什么?什么是惯用的书写方式test_h2 ?

最佳答案

我认为这两个 View 示例都应该重写为:

<%= test_h1 do %>
  <% 'test1' %>
<% end -%>

<%= test_h2 do %>
  <% 'test2' %>
<% end -%>

我的理解是 '<%=' 强制将块的输出呈现到输出流,这不是这两个示例中的预期行为

关于ruby-on-rails - 捕获 Rails View block 时的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53778131/

相关文章:

javascript - 使用 Rails 5 的谷歌分析不工作

ruby-on-rails - 1 个 Heroku dyno 上有多少个 Rails 应用程序?

ruby-on-rails - rake 和 bin/rake 的区别

mysql - Rails 升级包括方法行为更改

ruby-on-rails - 缺少图像文件的内部服务器错误 500 (Rails 3.2.12)

ruby-on-rails - 在 Rails config.action_controller.asset_host 上使用多个子域

javascript - Rails 5 中 JavaScript 编码 apostope 的问题

mysql - 验证同一个表中引用同一个表的两个外键

html - Rails 3 - link_to() - 在单个链接中需要多个文本段和单独的 HTML/CSS 类

ruby-on-rails-3.2 - 如何防止 Rails 在生产中使用 Action View 登录