Class: Navtastic::Renderer

Inherits:
Arbre::Context
  • Object
show all
Defined in:
lib/navtastic/renderer.rb

Overview

Generate HTML based on a menu

The actual HTML generation is done using the Arbre gem.

Calling #to_s will return the HTML.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.render(menu) ⇒ Renderer

Create a new renderer

Parameters:

Returns:


16
17
18
19
20
# File 'lib/navtastic/renderer.rb', line 16

def self.render(menu)
  new(menu: menu) do
    root(menu)
  end
end

Instance Method Details

#css_classes(item, context) ⇒ Array<String>

Decide which css classes are needed for this item

For example, the #item_container uses this to retrieve the css class for the current active item.

Parameters:

  • item (Item)

    the current item that is rendered

  • context (Symbol)

    which method is asking for the css classes

Returns:

  • (Array<String>)

    list of css classes to apply to the HTML element


65
66
67
68
69
70
71
72
73
74
# File 'lib/navtastic/renderer.rb', line 65

def css_classes(item, context)
  classes = []

  case context
  when :item_container
    classes << 'current' if item.current?
  end

  classes
end

#css_classes_string(item, context) ⇒ String

Same as #css_classes method, but joins classes together in a string

Returns:

  • (String)

See Also:


81
82
83
# File 'lib/navtastic/renderer.rb', line 81

def css_classes_string(item, context)
  css_classes(item, context).join ' '
end

#item_container(item) ⇒ Arbre::HTML::Tag

The container for every menu item (e.g. <li> tags)

Parameters:

Returns:

  • (Arbre::HTML::Tag)

38
39
40
41
42
# File 'lib/navtastic/renderer.rb', line 38

def item_container(item)
  li(class: css_classes_string(item, :item_container)) do
    item_content item
  end
end

#item_content(item) ⇒ Arbre::HTML::Tag

The item itself (e.g. <a> tag for links)

Parameters:

Returns:

  • (Arbre::HTML::Tag)

48
49
50
51
52
53
54
# File 'lib/navtastic/renderer.rb', line 48

def item_content(item)
  if item.url
    a(href: item.url) { item.name }
  else
    item.name
  end
end

#root(menu) ⇒ Arbre::HTML::Tag

The render starting point (e.g. root <ul> tag)

Parameters:

Returns:

  • (Arbre::HTML::Tag)

26
27
28
29
30
31
32
# File 'lib/navtastic/renderer.rb', line 26

def root(menu)
  ul do
    menu.each do |item|
      item_container item
    end
  end
end