为什么 ERB 不渲染这一行

Why ERB doesn't not render this line

我正在 Rails 之外渲染一个 erb 模板。该模板将保存为 html 文件并发送到其他地方,所以在我的代码中我有这个:

erb_file = "templates/banners/#{template}.html.erb"

erb_str = File.read(erb_file)

@city = options[:city]
@address = "#{@campaign.open_house_day} #{@case.open_house_from.strftime('%d/%m')} kl. #{@case.open_house_from.strftime('%H.%M')}-#{@case.open_house_to.strftime('%H.%M')}"
... 

renderer = ERB.new(erb_str)
result = renderer.result(binding)

FileUtils.mkdir_p('temp') unless File.directory?('temp')

File.open('temp/index.html', 'w') do |f|
  f.write(result)
end

所有内容都呈现良好,但 erb 只是忽略 @address 变量。为什么有任何想法?在我的代码中,如果我执行 puts @address 输出是预期的字符串。如果我做 puts @address.class 输出是一个字符串。我错过了什么?

请注意上面没有使用Rails

编辑

这是我用于呈现 html 的模板中的行:

<span class="wday"><%= @address %></span>

我能想到的主要是你没有在与 ERB 渲染相同的范围内设置实例变量。

您也可以尝试在 ERB 中定义 address

# make sure address is set first
# if it's not, you have a scoping problem
raise(ArgumentError) if @address.nil?

binding.local_variable_set :address, @address

puts ERB.new("<%= address %>").result binding