Embeded Blocks for Rails Erb

本文探讨了ERB模板中如何正确使用block.call与capture来输出内容的问题,并通过具体示例解释了concat函数的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

費了幾乎兩個小時搞定這問題。很干
不過也終於解開個超級大謎團,為什麼類似
<% list_as_tree @root do |item| %>
<div class="bubbleInfo">
<div class="trigger"><%= item.name %></div>
<div class="popup">
<%= addition_fun item %>
</div>
</div>
<% end %>
這樣的代碼能輸出內容呢。
原因很簡單,concat 魔法效果,而我就因為這個漏了這個函數浪費了近乎兩小時青春呀。

如果你使用 block.call(*p) 運行到這一步就會把運行結果輸出到erb中。
而如果使用了 capture ,他返回的是運行後的內容 而不乎自行添加到erb文件中,這時候就應該使用 concat 來輸出需要的內容了。

33: def capture(*args, &block)
34: # Return captured buffer in erb.
35: if block_called_from_erb?(block)
36: with_output_buffer { block.call(*args) }
37: else
38: # Return block result otherwise, but protect buffer also.
39: with_output_buffer { return block.call(*args) }
40: end
41: end

# Use an alternate output buffer for the duration of the block.
# Defaults to a new empty string.
def with_output_buffer(buf = '') #:nodoc:
self.output_buffer, old_buffer = buf, output_buffer
yield
output_buffer
ensure
self.output_buffer = old_buffer
end

這裡不過還是弄不清楚 block.call 的工作原理 。等自己哪天牛逼了再回頭解決
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值