YUI TreeView with Ruby on Rails

Here’s some code I’m using to generate a dynamic tree view using an acts_as_tree model with slug and title fields, the TreeView widget from YUI, and a Rails helper. I chopped out some of the code for clarity, so all this does is create a menu with the titles from the model, but the basic idea is there to expand on.

Rails view/JavaScript

<script type="text/javascript">
  var page_tree;
  page_tree_init = function () {
    page_tree = new YAHOO.widget.TreeView('page_tree');
    var root = page_tree.getRoot();
    <% generate_page_nodes(@root) {} %>


def generate_page_nodes(node, &block)
  parent = node.parent
  node_name = node.slug.gsub('-', '_')
  parent_node_name = parent.nil? ? 'root' : parent.slug.gsub('-', '_')
  js = <<-JS
    var #{node_name} = new YAHOO.widget.MenuNode('<span class="node_title">#{node.title}</span>',
  concat(js, block.binding)
  children = node.children
  children.each { |c| generate_page_nodes(c, &block) } unless children.empty?

4 thoughts on “YUI TreeView with Ruby on Rails

  1. var root = page_tree.getRoot();

    How can you pass javascript variable to a ruby function??
    As I am getting a nil at the function side..

  2. @Sachin

    In < % generate_page_nodes(@root) %>, @root is the root node of your acts_as_tree model.

  3. I’m getting problems running that generate_page_nodes method in the javascript block.
    undefined method `generate_page_nodes’

    help with this please

    1. @Joe

      Sorry, I can’t offer any support for this. I haven’t looked at this code in about a year, plus I ditched Ruby on Rails for Python/Pylons around the same time.

Comments are closed.