Rails宝典之六十九式: Markaby in Helper

看一个打印error_message相关的html的helper:
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


这么多html标签,写成String会灰常郁闷,而markaby库就是为简化我们的html标签的
或者说markaby是一种模板语言,它以插件的形式安装:
script/plugin install http://code.whytheluckystiff.net/svn/markaby/trunk


看看简化后的样子:
# 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

你可能感兴趣的:(html,.net,SVN,Rails)