You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails 7中如何向视图布局传递本地变量?

问题描述

我通过以下代码渲染视图:

action_controller.render_to_string(
    layout: 'document',
    template: 'administrator/users/export',
    encoding: 'UTF-8',
    formats: [:pdf],
    handlers: [:erb],
    locals: {
      testvar: "test"
    }
  )

尝试在指定的document布局中使用testvar变量:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html class="document">
<head>
  <title>
    <%= "Test: #{testvar}" %>
  </title>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width,initial-scale=1">
</head>
<body class="document pdf">
<%= yield %>
</body>
</html>

但出现异常:

*** NameError Exception: undefined local variable or method `testvar' for #ActionView::Base:0x000000000142f8

同时无法在布局中使用任何实例变量,该操作在Rails 6中可行,请问在Rails 7中该如何实现?

解决方案

在Rails 7中,locals参数仅传递给指定模板,布局默认无法直接访问这些局部变量,以下是三种可行的解决方式:

方式一:使用assigns传递实例变量

将变量放入assigns参数,这样模板和布局都能通过实例变量访问:

action_controller.render_to_string(
    layout: 'document',
    template: 'administrator/users/export',
    encoding: 'UTF-8',
    formats: [:pdf],
    handlers: [:erb],
    assigns: {
      testvar: "test"
    }
  )

布局中修改为实例变量调用:

<title>
  <%= "Test: #{@testvar}" %>
</title>

方式二:通过content_for从模板传递变量到布局

在模板administrator/users/export.erb中添加内容传递:

<% content_for :testvar, testvar %>

布局中通过content_for获取变量:

<title>
  <%= "Test: #{content_for(:testvar)}" %>
</title>

方式三:全局配置恢复Rails 6行为

如果希望整个应用回到Rails 6的变量传递逻辑,让布局自动继承模板的局部变量,可在config/application.rb中添加配置:

config.action_view.locals_inherits_from_controller = true

配置后,原代码无需修改即可正常运行,但该配置会影响所有视图的变量传递行为,需谨慎使用。

内容的提问来源于stack exchange,提问作者Carlos Martinez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 15:03:21