简体   繁体   中英

Render partial view with brackets

I'm just starting with rails. I'm trying to render partial view in my controller's method, but I'm gettin with brackets.

My appplication_controller.rb

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  def inline_error(field, messages_bag)
    if msg = messages_bag.errors.full_messages_for(field).first
      msg = '<small class="error">'+msg+'</small>'
      return msg.html_safe
    end
  end
  helper_method :inline_error

  #nevermind on param
  def take_flash(type)
    render "class/flash", :layout => false
  end
  helper_method :take_flash
end

my class/_flash.html.rb file:

hello

and I'm gettin

["hello"]

Could anybody help me?

In fact there are two different render methods, one is defined on ActionView, and the other one is defined on ActionController - they slightly differ in what they do. What you need here is render of the view:

def take_flash(type)
  view_context.render "class/flash"
end

I think you're confusing the usage of helpers and partials. They are both used to generate segments of view code but you don't need to use both at once. In your case you can either pass your param to the partial directly, and remove the helper.

Your view:

<%= render 'flash', locals: {my_param: 'blahblah'} %>

Your _flash partial:

Hello <%= blahblah %>

Or you can pass it to the helper and remove the partial.

Your view:

<%= take_flash('blahblah') %>

Your helper method (define this in a helper file, not your controller):

def take_flash(my_param)
  "Hello #{blahblah}"
end

Both approaches have the same outcome.

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