【问题标题】:Is it possible to use partials to be rendered as wrappers in Rails?是否可以在 Rails 中使用局部渲染作为包装器?
【发布时间】:2011-06-09 18:26:56
【问题描述】:

我想渲染这样的结构:

<tag1>
  <tag2 someattribute="somevalue">
    <.. lot of things inside ..>
  </tag2>
</tag1>

<tag1>
  <tag2 someattribute="someothervalue">
    <.. different inside things inside ..>
  </tag2>
</tag1>

tag1、tag2 是一样的,只是参数化了。代码的内部部分发生了变化。我试图像那样实现上面的东西(haml):

%div{id:['products', id]}
  .products_content
    %div{id:['products', id, 'content'], class:'products_mask'}
      = yield

这是从模板调用的部分 _content_head.html.haml:

= render 'shared/content_head', id: 'all' do
  %h3= Title
  %p= Body of the text.

我认为部分内部的 yield 会导致渲染传递的块的理论没有得到证明。有没有办法使用部分作为代码包装器?你能建议我一些解决方案如何达到这个目标吗?谢谢。

【问题讨论】:

    标签: ruby-on-rails-3 view rendering partial-views


    【解决方案1】:

    这可能是capture 方法的一个很好的用法。

    我只熟悉ERB,但大致思路如下:

    <% structure = capture do %>
      <h3>Title</h3>
      <p>Body of text</p>
    <% end %>

    然后将变量传入部分:

    &lt;%= render 'shared/content_head', :structure =&gt; structure %&gt;

    并在部分内,吐出structure变量:

    &lt;%= structure %&gt;

    在渲染局部时在视图中多次重置structure(或者更恰当地说,在帮助程序中?)。

    【讨论】:

    • 我发现您可以使用内联捕获,而不是先捕获然后再调用部分。它更具可读性。例如:&lt;%= render 'mypartial', :structure =&gt; capture { %&gt; inner content of your partial here, including more erb as needed, myvar=&lt;%= myvar %&gt;... &lt;% } %&gt;
    【解决方案2】:

    我使用了以下(Rails 4,但我认为它也应该适用于 Rails 3):

    <%# app/views/users/_edit.html.erb %>
    <%= render layout: 'modal_wrapping' do |f| %>
      <%= f.input :email %>
      ...
    <% end %>
    

    .

    <%# app/views/users/_modal_wrapping.html.erb %>
    <div id='modal'>
      <%= simple_form_for @user do |f| %>
        <%= yield f %>
      <% end %>
    </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-16
      • 2016-11-12
      • 1970-01-01
      • 1970-01-01
      • 2013-06-20
      • 2015-10-23
      • 1970-01-01
      相关资源
      最近更新 更多