0

Following code should accept nested code and yield in 'li' tag

def sidebar_link(text,link, color = nil)
  recognized = Rails.application.routes.recognize_path(link)
  output = ""
  content_tag(:li, :class => ( "sticker sticker-color-#{color}" if color) ) do
  if recognized[:controller] == params[:controller] && recognized[:action] == params[:action]
    output << link_to( text, link, :class => 'lead')
  else
    output << link_to( text, link) 
  end
  output << yield if block_given?
  raw output
 end
end

in HAML view:

      %ul
        = sidebar_link 'Tickets', tickets_path, :orange do
          %ul.sub-menu
            = sidebar_link "Service Requests #{ServiceRequest.all.count}", service_requests_path
        = sidebar_link 'Problems', problems_path, :green
        %li.divider
        = sidebar_link 'Clients', clients_path, :blueDark
        = sidebar_link  'Services', services_path, :red do
          %ul.sub-menu
            = sidebar_link 'Categories', categories_path

This produces correct HTML except first link. Output does not contain "Tickets" word, but everything else seems to be fine.

So why this strange behaviour can occure? Helper recursion messes "output" variable?

Max Prokopov
  • 1,308
  • 11
  • 16

1 Answers1

2

I found solution to explicit use &block as following

def sidebar_link(text,link, color = nil, &block)
 recognized = Rails.application.routes.recognize_path(link)
 output = ""
 content_tag(:li, :class => ( "sticker sticker-color-#{color}" if color) ) do
  output << link_to( text, link, :class => ( 'lead' if recognized[:controller] == params[:controller] && recognized[:action] == params[:action]) )
  output << capture(&block) if block_given?
  raw output
 end
end
Max Prokopov
  • 1,308
  • 11
  • 16