From: Jano Svitok Date: 2007-03-23T20:52:33+09:00 Subject: Re: Newbie templating question: how to combine multiple files On 3/23/07, Frank Reiff wrote: > Hi, > > I use ERB for some very basic HTML templating (no Rails!). In essence, I > have normal HTML pages produced by Adobe GoLive (the WORST HTML editor > ever) with a couple of simple tags along the lines of <%= > @myProduct.price %>. > > Now, I'm planning to replace GoLive's templating mechanism with ruby. > > Ideally, the solution would look something like this: > > * each file is a simple HTML file that remains editable in a normal HTML > editor, e.g. > > >

Hello World

> > > > * the template itself is an HTML file that remains editable in a normal > HTML editor, something along these lines: > > >
<%= headertag() %>
>
> <%= content() %> >
> > > > > Looking at the documentation for the ERB class, I can't find a simple > way of including another template inside a template file. I guess I > could simply do a require, but that will simply copy the entire contents > of the file as ruby code. How do you usually subdivide your templates > into multiple files (e.g. header, variable content, footer, etc.) using > ERB? > > Are there any better templating solutions available that could deal with > combining multiple HTML pages into a single one? > > Any help would be appreciated. > > Best regards, > > Frank > Hi Frank, have a look at rails source how it is done. It's quite easy. The following code I almost copied from there (I do template caching in a member attribute in addition). I include this code in the object that renders the templates, but with a little modifications, you can use it from top level scope as well (e.g. after you get rid of @'s) def render(template, local_assigns = {}) b = evaluate_locals(local_assigns) rhtml = @templates[template] if rhtml.nil? template_filename = File.join(@template_dir, template) rhtml = ERB.new(File.read(template_filename), nil, "%<>") @templates[template] = rhtml end rhtml.result(b) end def evaluate_locals(local_assigns = {}) b = binding local_assigns.each { |key, value| eval "#{key} = local_assigns[\"#{key}\"]", b } b end HTH, Jano