Last Updated: October 05, 2022
·
3.133K
· subosito

Writing HTML easily on decorator / helper

Writing HTML code inside decorator/helper is sucks, right?. For example:

class UserDecorator < ApplicationDecorator
  def foo
    f = h.content_tag :ul, class: 'fancy' do
      h.concat h.content_tag :li, h.link_to('home', h.root_path)
      h.concat h.content_tag :li, h.content_tag(:p, "nightmare!")
    end
    f + h.content_tag(:div, "baz")
  end
end

What about if we can write something like this?

class UserDecorator < ApplicationDecorator
  def foo
    build_html do
      ul class: 'fancy' do
        li { @h.link_to('home', @h.root_path) }
        li do
          p 'awesome!'
        end
      end
      div 'baz'
    end
  end
end

Feels better right?. But, how we do that?. This tip will show you how.

Edit your Gemfile:

gem 'mab'
gem 'draper'

And create build_html inside your ApplicationDecorator, or you can use Mab::PrettyBuilder directly:

class ApplicationDecorator < Draper::Decorator
  def build_html(assigns = {}, &blk)
    Mab::PrettyBuilder.new({source: source, h: h}.deep_merge(assigns), nil, &blk).to_s.html_safe
  end
end

That's it. You can also use this technique inside helper. Read more about 'Mab' on https://github.com/camping/mab.

1 Response
Add your response

Thank you very much for this code:

h.content_tag :ul, class: 'fancy' do

h.concat h.content_tag :li, h.link_to('home', h.root_path)

h.concat h.content_tag :li, h.content_tag(:p, "nightmare!")

end

This really saves me a lot of time, I'll try mab gem next time :)

over 1 year ago ·