Jason Jason - 1 year ago 59
Ruby Question

Ruby: How to use generate HTML with dynamic values?

I am writing a Ruby script that will generate a large flat HTML menu for my website, I could generate this menu on the fly each time a page loads, but I think doing so is a waste of resources, especially as this will almost never need to change.

I want to effectively do the following (in semi-sudocode):

part_of_my_menu = eval %{

<script type="text/javascript">
var mapper = new Array();
<% parent_categories.each_with_index do |parent_category,i| -%>
mapper["#{parent_category.name}"] = <%= i -%>;
<% end -%>


and then be able to write the part_of_my_menu string variable to a HTML file (this I can do).

I know this is not how eval works in Ruby but does anyone know how to achieve this same "wrapper" functionality?

(fyi - the code I want to wrap with my "eval" function is much longer than this, I've only posted a very small snippet to illustrate what I am trying to achieve)



ERB is part of the standard library so you could do things like this:

tmpl = %q{<script type="text/javascript">...</script>}
erb  = ERB.new(tmpl)
parent_categories = [ ... ]
part_of_my_menu = erb.result

The ERB documentation contains some good examples of how to use it.

You don't need a hand rolled eval construction, you can use standard existing libraries and your existing knowledge.