2012-08-27 45 views
0

是否可以從哈希渲染反轉模板?如果不是,一個人如何構建對應的哈希一個複雜的模板,例如:從哈希渲染反轉模板

{ :a => [ { :b => 'foo', :c => 'bar' }, { :d => 'blah', :e => 'blubb'} ] } 

不幸的是,用戶指南不顯示這樣的例子。

回答

0

這取決於你想如何渲染散列。假設代碼:

require 'inversion' 

the_hash = { :a => [ 
    { :b => 'foo', :c => 'bar' }, 
    { :d => 'blah', :e => 'blubb'} 
    ] } 

可以渲染它,當然是:

<!-- prettyprint.tmpl --> 
<code><?pp the_hash ?></code> 

然後:

tmpl = Inversion::Template.load('prettyprint.tmpl') 
tmpl.the_hash = the_hash 
puts tmpl.render 

這將作爲渲染:

<!-- prettyprint.tmpl --> 
<code>{:a=&gt;[{:b=&gt;"foo", :c=&gt;"bar"}, {:d=&gt;"blah", :e=&gt;"blubb"}]}</code> 

假設你想做一些更復雜的事情散列,像渲染它的一些成員:

<!-- members.tmpl --> 
A's first B is: <?call the_hash[:a].first[:b] ?> 
A's first C is: <?call the_hash[:a].first[:c] ?> 
A's second D is: <?call the_hash[:a][1][:d] ?> 
A's second E is: <?call the_hash[:a][1][:e] ?> 

其中(具有相同的代碼,除了加載「members.tmpl」,而不是在前面的例子)會使像這樣:

<!-- members.tmpl --> 
A's first B is: foo 
A's first C is: bar 
A's second D is: blah 
A's second E is: blubb 

但是建築像你的哈希這樣的大型複雜數據結構,然後將它與模板合併並不是真正意圖如何使用Inversion。這個想法實際上是加載模板爲您提供了一個帶有API的Ruby對象,適合在渲染之前傳遞和增量添加東西。而不是建立一個哈希的,只是通過模板對象自身周圍,並調用它的存取,然後讓它拔出它需要構建視圖:

tmpl.users = User.all 
tmpl.company = "ACME Widgets, Pty" 
tmpl.render 

這也有被更適合嘲諷優勢:

# (rspec) 
tmpl = mock("members template") 
tmpl.should_receive(:users).with(User.all) 
tmpl.should_receive(:company).with(company_name) 
tmpl.should_receive(:render).and_return("the rendered stuff") 

這將完全從測試中刪除模板內容,並只關注控制器應發送給視圖的消息。

有一個相當全功能的例子in the manual,以及the code that renders it

該庫(及其文檔)是相當新的,所以感謝提出這一點。我有一個掛起的補丁將the manual與API文檔合併,這應該有所幫助,但同時它可能是找到示例的最佳位置。

希望這會有所幫助。我很樂意親自回答更深入的問題(gee在FaerieMUD.org上),或者通過GithubBitbucket上的請求接受修補程序。

+0

太棒了,非常感謝! – christina