代码之家  ›  专栏  ›  技术社区  ›  Alexander Azarov

捕获Rails视图块时出现差异

  •  7
  • Alexander Azarov  · 技术社区  · 6 年前

    我有两个街区的ERB视图:

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

    test_h1 test_h2 helper_method 在控制器中:

    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
    

    测试单元h2

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

    为什么?什么是惯用的写作方式 ?

    4 回复  |  直到 6 年前
        1
  •  3
  •   Aleksey Studnev    6 年前

    我认为这两个观点的例子都应该改写为:

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

    我的理解是,“<%=”强制将块的输出渲染到输出流,这在这两个示例中不是预期的行为

        2
  •  2
  •   Benjamin Bouchet    6 年前

    使用时 capture <%= 从您的erb的开始,将立即输出到页面输出。

    <% 而是在你的 test_h2 块因此,要获得这两种情况下的预期行为,请使用以下语法:

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

    本文中的更多信息: https://thepugautomatic.com/2013/06/helpers/

        3
  •  2
  •   Vasfed SAJITHA MARIYAM    6 年前

    capture 重写当前输出缓冲区并仅调用块(该块仍绑定到其他视图上下文),因此从控制器调用时重写无效,因为 view_context 与正在渲染视图的上下文不同。

    要处理上下文,您可以这样定义助手:

    # in controller
    helper do
      def test_h3(&block)
        # this will run in view context, so call `controller.some_func` to access controller instance
        link_to '/url' do
          capture(&block)
        end
      end
    end
    
        4
  •  -1
  •   shirish    6 年前

    在rails中实现这一点的idomatic方法是将test_h2方法移动到一个关注点,并将该关注点包括在controller和helper类中。

    或者在控制器类中将test_h2定义为helper_方法。



    另外,如果您需要视图的方法,那么在帮助程序中包含关注点或定义您自己的方法。

    参考 Can we call a Controller's method from a view (as we call from helper ideally)?
    How to use concerns in Rails 4