2016-11-09 40 views
1

我在Rails之外渲染一個erb模板。模板是要保存爲HTML文件和其他地方發送,所以在我的代碼,我有這樣的:爲什麼ERB不會渲染這一行

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 

的所有內容呈現正常,但該局根本不理@address變量。任何想法爲什麼?雖然在我的代碼中,如果我做puts @address輸出是預期的字符串。如果我做puts @address.class輸出是一個字符串。我錯過了嗎?

請注意,上面並沒有使用Rails的

編輯

下面是我的模板行,我用它來呈現HTML:

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

你使用@address?如果是的話,在哪裏以及如何? –

+0

@Eric Duminil我已經添加了模板的片段,呈現字符串 – WagnerMatosUK

+0

A [mcve]將有極大的幫助。 –

回答

0

主要的事情,我可以想想你是不是將實例變量設置在與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 
+0

這很可能是這種情況(錯誤的範圍) –