lost password?

home
•  xaraya
•  rails +
•  django
•  webdev
•  xamp
•  musings

rss
Tag this page
   

ยป Blogs that link here
last modified: Jun 02, 2007
(first posted: Jun 02, 2007)
(1211 Reads)
keywords: helpers templates
Permalink

template info helper

Here's a neat little helper you might like which displays the name of the current template file and other information, especially for development and debugging.

 

I wanted to show the template names for a given page. The template code could look something like this:

<%= template_info %>

or

<%= template_info @page.updated_at %>

or even

<%= template_info @page.updated_at, "by #{@page.author.name}" %>

The last example would generate something like this html:

<div class="template_info">
Template: pages/show.html.erb<br />
Data updated: 31 May 16:31<br />
by Jonathan
</div>

Here it is. Just add this to application_helper.rb. Note, the file name is always displayed. If a date or time is provided (update arg) it will be shown. Then you can add any number of additional strings to also be shown.

 

  def template_info( update = nil, *info )
    if RAILS_ENV == "development"
      info.insert(0, "Data updated: " + update.to_s(:short)) if update
      f = caller[0]
      f = f[0,f.index(':')]
      f = f.split("/").last(2).join("/")
      info.insert(0, "Template: #{f}")
      content_tag("div", info.join("<br />"), :class => "template_info" )
    end
  end

A couple of changes I might make. Instead of keying directly off RAILS_ENV, I've setup a constant hash in environment.rb with some options including

SITE_OPTIONS = { "template_info" => true }

Then the "if" is more like

if SITE_OPTIONS.fetch('template_info', false) 

(using fetch allows the hash key to be undefined and then default to false).

Also, instead of contact_tag("div", it may be better to embed the info in html comments <!-- --> so its only visible in source view. In fact, maybe the value of 'template_info' could be "div", "comment", or false and do a case switch (I don't think content_tag lets you specify "<!--").

Finally I'd prefer if this were injected into the render method, so all templates would display their name when enabled. Xaraya framework has that and I miss it.

 

 

There are no comments attached to this item.

Post a new comment

How many days in a week?

Name :