简体   繁体   中英

Rails 4 render partial with locals

I have a partial _errors.html.haml to display the form errors in my application. The code inside the partial:

.errors
  %ul
    - errors.full_messages.each do |message|
      %li= message

I am rendering the partial from projects/new.html.haml as

= render 'shared/errors', locals: { errors: @project.errors } if @project.errors.any?

The errors partial resides in views/shared directory.

But I get an error when I try to render the errors partial.

undefined local variable or method errors' for #<#<Class:0x0055895405bbc0> :0x00558951a80fe0>

If I change the rendering line to

= render 'shared/errors', errors: @project.errors if @project.errors.any?

it works. Why doesn't using locals work in this case?

Just to add on Khanh's answer. I have experimented all the variation. It seems that if you would like to use the term locals for Rails partial rendering, you would need to specify the keyword partial .

Explicit So this would work

= render partial: 'shared/errors', locals: { errors: @project.errors } if @project.errors.any?

Implicit Or the short form would be

= render 'shared/errors', errors: @project.errors if @project.errors.any?

So in conclusion, if you specify the hash key for rendering partial, all its key has to be specified explicitly. Else you would have to not specify the hash key and let rails figure out implicitly based on the position.

I guess that your problem is making condition for locals .

You can try to do this:

- if @project.errors.any?
  = render partial: 'shared/errors', locals: { errors: @project.errors }

In _errors.html.haml

.errors
  %ul
    - test_errors.full_messages.each do |message|
      %li= message

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM