开发者

Ruby: How to use generate HTML with dynamic values?

开发者 https://www.devze.com 2023-04-02 02:07 出处:网络
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, especia

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 -%>
</script&g开发者_Python百科t;

}

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)

Thanks!


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.


You might be interested in the dom gem that I have developed. You can generate HTML strings like this:

require "dom"
["foo".dom(:span, class: "bold"), "bar"].dom(:div).dom(:body).dom(:html)
# => "<html><body><div><span class=\"bold\">foo</span>bar</div></body></html>"
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号