用haml显示错误消息

时间:2012-02-18 18:39:59

标签: ruby-on-rails ruby-on-rails-3 haml

这是我的表格:

= form_for @talent do |f|

  - if @talent.errors.any?
    #error_explanation
      %h2= pluralize(@talent.errors.count, "error")
      "prohibited this user from being saved:"
         %ul - @talent.errors.full_messages.each do |msg|
           %li= msg

  = f.label :First_Name
  = f.text_field :first_name
  = f.label :Last_Name
  = f.text_field :last_name
  = f.label :City
  = f.text_field :city
  = f.label :State
  = f.text_field :state
  = f.label :Zip_code
  = f.text_field :zip_code
  = f.label :Email
  = f.text_field :email
  = f.submit "Create"

这是我的错误消息:

Illegal nesting: nesting within plain text is illegal.

Extracted source (around line #7):

4:     #error_explanation
5:       %h2= pluralize(@talent.errors.count, "error")
6:       "prohibited this user from being saved:"
7:         %ul - @talent.errors.full_messages.each do |msg|
8:           %li= msg
9: 
10:   = f.label :First_Name

我无法弄清楚我做错了什么。

2 个答案:

答案 0 :(得分:3)

首先,您的%ul行应该是自己的,并且它下面有循环。此外,您的%ul行不应缩进上面的字符串:

- if @talent.errors.any?
  #error_explanation
    %h2= pluralize(@talent.errors.count, "error")
    "prohibited this user from being saved:"
    %ul
      - @talent.errors.full_messages.each do |msg|
        %li= msg

但你可能想要的是“禁止......”部分成为你h2的一部分?如果是这样的话:

- if @talent.errors.any?
  #error_explanation
    %h2
      = pluralize(@talent.errors.count, "error")
      "prohibited this user from being saved:"
    %ul 
      - @talent.errors.full_messages.each do |msg|
        %li= msg

答案 1 :(得分:2)

如果您要在标记中放置多个内容,就像使用h2一样,则需要将它们全部缩进而不是内联并添加第二个内容。 Haml认为您正试图将ul嵌套在其上方的文本中。

= form_for @talent do |f|

  - if @talent.errors.any?
    #error_explanation
      %h2
        = pluralize(@talent.errors.count, "error")
        "prohibited this user from being saved:"
      %ul - @talent.errors.full_messages.each do |msg|
        %li= msg

或者,如果您不想要h2内的文字,那么您的ul错误就会缩进。把它带回两个空间。

#error_explanation
  %h2= pluralize(@talent.errors.count, "error")
  "prohibited this user from being saved:"
  %ul - @talent.errors.full_messages.each do |msg|
    %li= msg