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.
Written by Alif Rachmawadi
Related protips
1 Response
![](https://coderwall-assets-0.s3.amazonaws.com/uploads/user/avatar/115399/default_profile_3_normal.png)
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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#