Rails宝典之六十九式: Markaby in Helper
百里胜泫
2023-12-01
看一个打印error_message相关的html的helper:
[code]
module ApplicationHelper
def simple_error_message_for(object_name)
object = instance_variable_get("@#{object_name}")
return if object.errors.empty?
result = '<div id="error_message">'
result += "<h2>#{pluralize(object.errors.count, 'error')} occurred</h2>"
result += "<p>There were problems with the following fields:</p>"
result += "<ul>"
object.errors.each_full do |msg|
result += "<li>#{msg}</li>"
end
result += "</ul>"
result += "</div>"
result
end
end
[/code]
这么多html标签,写成String会灰常郁闷,而markaby库就是为简化我们的html标签的
或者说markaby是一种模板语言,它以插件的形式安装:
[code]
script/plugin install http://code.whytheluckystiff.net/svn/markaby/trunk
[/code]
看看简化后的样子:
[code]
# in helper
def simple_error_messages_for(object_name)
object = instance_variable_get("@#{object_name}")
return if object.errors.empty?
markaby do
div.error_messages! do
h2 "#{pluralize(object.errors.count, 'error')} occurred"
p "There were problems with the following fields:"
ul do
object.errors.each_full do |msg|
li msg
end
end
end
end
end
def markaby(&block)
Markaby::Builder.new({}, self, &block)
end
[/code]