[英]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.