Reputation: 8043
Let's pretend we have a Rails project with a class named Foo
residing in the lib
directory.
We want to generate some HTML based on its attributes.
Now, creating a big string by concatenating HTML fragments appropriately doesn't feel right in the least bit.
My question is: is there a blessed way to do it?
Upvotes: 0
Views: 526
Reputation: 1278
You have a couple pretty straightforward options. If you're using ERB, you can do something like:
ERB.new(File.read(the_file_path)).result
I'm using a library called Tilt (https://github.com/rtomayko/tilt) in one of my applications to render a HAML template. Here's the exact sausage factory code that I'm running right now:
template = Tilt.new(ITEM_TEMPLATE) # ITEM_TEMPLATE is the path of a .haml file
template.render nil, {:item => item, :item_details => item_details}
# item and item_details are now available as local variables in the partial
If you don't want to go the templating route, you could try something like Erector (http://erector.rubyforge.org/userguide.html) as well.
Worst case scenario: instead of concatenating fragments, you could use the HEREDOC to format it nicely:
<<-HTML
<div id="foo">
<span class="bar">#{thing.method}</span>
<div>#{thing.attribute}</div>
</div>
HTML
Upvotes: 3