【问题标题】:Can you render only part of a partial for a particular action?你可以只渲染特定动作的一部分吗?
【发布时间】:2015-02-27 14:52:38
【问题描述】:

我有一个商品部分,其中包含商品图片、商品价格和商品描述等内容。在项目部分中,我还有一个用户头像的小缩略图,因为它是一个 p2p 市场。我希望这个头像呈现在我<%= render @items %> 的任何地方,除了用户个人资料页面(用户控制器,显示操作),我希望它停止,因为它是多余的。

有没有办法做到这一点?我已经尝试了很多事情,甚至还没有接近。谢谢你的帮助。

这里是项目部分代码:

<div class="thumbnail">
          <%= link_to item_path(item) do %>
          <%= image_tag(item.image.url(:thumb)) %>
          <% end %>
      </div>

      <div class="caption">
        <% if item.user.avatar.url %>
          <%= link_to item.user do %>
            <%= image_tag(item.user.avatar.url(:thumb), class: "user-avatar-partial pull-left") %>
          <% end %>
        <% else %> 
          <%= link_to item.user do %>
            <%= image_tag 'avatar-thumb.png', class: "user-avatar-partial pull-left" %>
          <% end %>
        <% end %>
          <span id="item-name-partial"> 
            <%= link_to item_path(item) do %>
              <%= item.name.truncate(20) %>
            <% end %>
          </span>
            <span class="pull-right" id="item-price-partial"> 
              <%= link_to item_path(item) do %>
                <%= number_to_currency item.price %>
              <% end %>
            </span>
      </div> 

【问题讨论】:

    标签: ruby-on-rails-4 partials


    【解决方案1】:

    我可以想到两种解决方案,但在这两种解决方案中,您都必须在部分代码中稍作修改。

    解决方案 1:

    在控制器动作中设置一个实例变量并在你的部分中使用它。

    class UsersController
      def show
        @hide_small_thumbnail = true
        # rest of your code
      end
    end
    

    然后在你的部分:

    <% unless @hide_small_thumbnail %>
      <% #code for showing the thumbnail %>
    <% end %>
    

    除了该特定操作之外,实例变量的值将是 nil,因此您的缩略图将按原样显示。

    解决方案 2:

    在您的视图中指定控制器和操作名称。例如:

    <% condition_one = (controller.controller_name == 'users') %>
    <% condition_two = (controller.action_name == 'show') %>
    <% unless condition_one && condition_two %>
      <% #code for showing the thumbnail %>
    <% end %>
    

    如果我必须选择,我会选择第一个。但是,如果您使用后者,最好将条件移动到辅助方法并使用辅助方法,而不是您认为的详细条件。

    【讨论】:

    • 谢谢。我会尝试两者,让每个人都知道什么是有效的(如果成功则接受答案)。
    • 我选择了第一个解决方案,它就像一个魅力。非常感谢您提供解决方案。
    猜你喜欢
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    • 1970-01-01
    相关资源
    最近更新 更多