Rails:允许部分只渲染一次 [英] Rails: allowing a partial to only be rendered once

查看:41
本文介绍了Rails:允许部分只渲染一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法对 rails partial 进行编码,使其只能渲染一次,无论包含视图尝试渲染多少次?

Is there a way to code a rails partial such that it can only be rendered once, no matter how many times the containing view attempts to render it?

原因:一个页面由一系列较小的小部件部分组成.每个小部件在右上角都有一些小链接,用于显示弹出窗口"表单,这些表单从用户那里收集数据.这些弹出窗口是小部件部分包含的部分.单击这些链接会在 DOM 中找到 popover 部分(按 id),显示它,并将其放置在单击的链接下方.小部件部分无法知道此页面中还包含哪些其他小部件,但我想在 DOM 中包含一次且仅一次所需的弹出窗口.

Why: A page consists of a series of smaller widget partials. Each widget has a few small links in the upper right to display "popover" forms, which collect data from the user. These popovers are partials included by the widget partials. Clicking these links finds the popover partial in the DOM (by id), displays it, and positions it below the clicked link. The widget partials have no way of knowing which other widgets are included in this page, but I want to include each required popover once and only once in the DOM.

如果这仍然令人困惑,设置类似于

If this is still confusing, the setup is something like

  • 页面视图
    • 小部件部分 1
      • 弹出部分A
      • 弹出部分B
      • Popover 部分 C
      • 弹出部分B
      • 弹出部分 D

      这里 A、B、C 和 D 都应该在 DOM 中只出现一次,尽管 B 被明确包含了两次.

      Here A, B, C, and D should each appear only once in the DOM, despite B being explicitly included twice.

      我在想像 C 中的 #ifndef 这样的东西,我们确保标题只包含一次.

      I'm thinking something like #ifndef in C, where we ensure headers are included only once.

      注意:我使用的是 Rails 2.3

      Note: I'm using Rails 2.3

      推荐答案

      您可以使用实例变量.但是,您必须确保实例变量仅绑定到视图并且不会崩溃.

      You could make use of the instance variables. However, you have to ensure that the instance variables is bounded to the views only and will not be crashed.

      类似于:

      # in your view
      <% @widget_partial_rendered_popovers ||= [] %>
      
      <% popover_partials.each do |pp| %>
        <% if !@widget_partial_rendered_popovers.include?(pp) %>
          <% @widget_partial_rendered_popovers << pp %>
          display the popover
        <% end %>
      <% end %>
      

      如果您能够在控制器的早期收集弹出框的东西,那么将所有弹出框渲染在一个地方会更干净.因为我不知道你的确切结构是什么,我只能给你你需要的东西.

      If you are able to collect the popover things early in the controller, it would be cleaner to just render all the popovers in a place. As I don't know what's your exact structure is, I could just give you what you have required.

      这篇关于Rails:允许部分只渲染一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆