[英]Rails - Pass options into a helper method that accepts a block?
我有一個創建郵件模板行(html)的助手。 我希望能夠將樣式傳遞給行(可選),例如背景色。
module MailHelper
def module_row(&block)
h << "<table border='0' cellpadding='0' cellspacing='0' width='100%'>"
# more table html here
h << capture(&block)
# more table html here
h << "</table>"
raw h
end
end
我希望能夠有選擇地傳遞背景色,但是在傳遞“&block”時似乎無法弄清楚該如何做。 在Ruby中有可能嗎?
你當然可以!
module MailHelper
def module_row(options={}, &block)
...
if options[:foo]
do_foo_stuff
end
end
end
<% module_row(foo: true) do |x| %>
...
<% end %>
常見的做法是定義默認值,如下所示:
def module_row(options={}, &block)
opts = {
foo: true,
background_color: 'black'
}.merge!(options)
if opts[:foo]
do_foo_stuff
end
end
您可以將選項作為哈希很好地傳遞,例如:
module MailHelper
def module_row(**opts, &block)
bgcolor = opts[:bgcolor] || '#FFFFFF'
...
h << "<table border='0' cellpadding='0' cellspacing='0' width='100%'>"
# more table html here
h << capture(&block)
# more table html here
h << "</table>"
raw h
end
end
然后,您可以致電:
module_row(bgcolor: '#AAAAAA', &my_block)
要么:
module_row(bgcolor: '#AAAAAA') { block content }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.