basaah asked:

passing arguments to a Element

Tags:

hello, I was wondering if the above is possible. I mean like this way.

def foo
 @bar = 8
end
now in foo.xhtml I can call @bar and then get 8,
...
<span if="@bar = 8">jeeh</span>
...
that works but when I do it this way
class Page < Nitro::Element
  def render 
    %{
   <html>
    <head>   
      <title>#{@title}</title>
    </head>  
    <body>
    <span if="@bar = 8">
        #{content} 
    </span>  
    </body>
    </html>
    }
  end 
end 
 
and then foo.xhtml
<Page title="hoihoi">
 jeeh
</Page>

but then @bar is nil in the element page, this is logic because it is not an instance variable of the element class, but how can I then pass arguments from the template to the element?

btw. I put a session variable in the instance variable so if you can use session one way or another in a element it is fine too?

(1 attempts)

dickdawg answered:

Each attribute set on the element in your xhtml document will be visible as an instance variable to the class implementing the element (Page, in this case). So for:

<Page bar="8" title="My Page">...</Page>
The @bar instance variable will be visible inside the Page#render method and it's value will be `8'. Then for the conditional rendering, you could do the following:
class Page < Nitro::Element
  def render
    out = %~
    <html>
      <head>   
        <title>#{@title}</title>
      </head>  
      <body>
    ~
    if @bar == 8
      out += %~
        <span>
          #{@_text}
        </span>
      ~
    end

    out += %~  
      </body>
    </html>
    ~

    out

  end
end
This is how you would pass a variable from the xhtml template to the Page instance, although I'm not sure whether that answers your question, as you seem to require post processing of the output of your `render' method, and I'm not sure whether processing happens after all Nitro::Element instances have been rendered or before. Either way, it would just require a simple test on your part to figure that out. Also, notice that @_text holds the literal content of the Page element... meaning that if you put html in there, then it would render that html. There is also a @_children instance variable which, presumably, contains child nodes which are also Nitro::Element derivatives

Rating: 5