manveru is proud to present you this little tip:

Using Elements

This is a quick guide how elements work in nitro and how you can yield all their power with just a few keystrokes.

let's jump in - the following code usually is put in a file called 'skin.rb' and required in run.rb right at the place where one requires the controller and model.

hopefully you know how to do that, since i won't cover it in this little tip.

so let's start:

# skin.rb

class Page < Nitro::Element
  def render
    %{
    <html>
      <head>
        <title>Foo</title>
        </head>
      <body>
        <h1>\\</h1>
        #{content}
      </body>
    </html>
    }
  end
end

Ok, now we have a new class called 'Page' and it has two methods. now, how to tell nitro what the heck it should do with it...

assume a very simple template:

<p>Hello World</p>

simple, huh?

now, to tell nitro we want this element used in this template is simple as:

<Page>
<h1>Hello World</h1>
</Page>

and voila! you have merged them - the stuff between <Page></Page> is placed where you have #{content} in the element. the render-method of the element with the name of the tag is called when nitro encounters a element in a template and it calls the #render method of it.

so far everything clear?

ah, yeah - i added a \ because it's really useful and not widely known - also to demonstrate how to use variables in the element, since you have to be careful and escape them or place stuff in so it is only evaluated at runtime. of course you can try to unescape it and watch nitro explode :)

now on to the next helper... using methods within elements (apart from #render)

# skin.rb

class Page < Nitro::Element
  def render
    %{
    <html>
      <head>
        <title>Foo</title>
        </head>
      <body>
        <h1>\\</h1>
        #{menu}
        #{content}
      </body>
    </html>
    }
  end
  def menu
    items = [:home, :foo, :bar]
    %{
      <?r items.each do |item| ?>
        <a href="/\\#{item}">\\#{item}</a>
      <?r end ?>
     }
  end
end

yo, easy eh? now you have a fancy menu on every page you put <Page></Page>

give me a notice on #nitro (irc.freenode.net) if you want to know more and i'll assemble a more extended tip, thanks for reading...