ruby-on-rails 在Rails中使用局部变量渲染布局

64jmpszr  于 2023-04-22  发布在  Ruby
关注(0)|答案(1)|浏览(161)

在我的rails控制器中,我有一个呈现特定布局的动作:

def registrations_for_user
      render layout: 'remote_modal', locals: { modal_title: I18n.t('organizations.enrolled_in_learning_item.title') }
    end

这个布局需要本地modal_title才能工作,这就是为什么我把它传递到那里。下面是布局:

<div class="relative px-4 w-full max-w-6xl md:h-auto">
  <!-- Modal content -->
  <div class="relative bg-white rounded-lg shadow dark:bg-gray-700">
    <!-- Modal header -->
    <div class="w-full">
      <div class="flex justify-between items-start p-5 rounded-t">
        <div class="w-full-0">
            <h3 class="text-lg font-semibold text-gray-900 dark:text-white">
              <%= modal_title %>
            </h3>
        </div>
        <i class="close-modal fas fa-times text-lg cursor-pointer"></i>
      </div>
    </div>
    <!-- Modal body -->
    <div class="px-6">
      <div class="w-full">
        <%= yield %> 
    </div>
  </div>
</div>

但我一直得到:

NameError - undefined local variable or method `modal_title' for #<ActionView::Base:0x000000000656f8>:
  app/views/layouts/remote_modal.html.erb:9

在rails中不能将local传递给布局吗?有没有其他方法可以做到这一点?我读过一些建议使用@variable的答案,但这似乎不是一个干净的方法。

rkue9o1l

rkue9o1l1#

你需要在你的控制器中定义它根据路由你可以做一些像

def local
@x = current_user.model.title #define your logic
end

那么在你看来<%= @x %>

相关问题