2009-09-15 51 views
0

我希望看到單詞「測試」出現在輸出一次,單詞「你好」出現一次。erb:輸出重複,如果模板包含方法定義

但我很困惑,如果我這樣做,單詞「測試」顯示兩次

<div> 
    <h3>test</h3> 
</div> 

<% def helo %> 
<% "hello" %> 
<% end %> 

<%= helo %> 

我假設有一個簡單的解釋,這與erb的一些怪癖有關?

+0

如果你檢查原始html是否測試字出現在一個div和一個h3?你有佈局文件,可能再次包含文本?你可以發佈原始html輸出嗎 – 2009-09-15 08:21:53

+0

我無法解釋發生了什麼,但你不應該這樣做。 您無法控制helo方法定義在哪個對象上。你也不能控制如何將<%...%>翻譯成Ruby。 所以你正在調用未知對象的未知方法。結果是不可預測的並不令人驚訝。 – 2009-09-15 11:22:03

回答

1

我試了一下:

require 'erb' 

template = %q{ 
    <div> 
     <h3>test</h3> 
    </div> 

    <% def helo %> 
     <% "hello" %> 
    <% end %> 

    <%= helo %> 
} 

t = ERB.new(template) 
puts t.result 

#(erb):6:in `helo': undefined local variable or method `_erbout' for main:Object (NameError) from (erb):10 

如此看來你提什麼是正確的,但所有的怎麼樣了,你可以很容易地欺騙它:

require 'erb' 

template = %q{ 
    <div> 
     <h3>test</h3> 
    </div> 

    <% def helo 
     "hello" 
    end %> 

    <%= helo %> 
} 

message = ERB.new(template) 
puts message.result 

而且它爲我工作。