开发者

How to use string interpolation when rendering templates?

开发者 https://www.devze.com 2022-12-28 04:50 出处:网络
I开发者_StackOverflow found this code in a Rails cookbook. class BlogController < ApplicationController

I开发者_StackOverflow found this code in a Rails cookbook.

class BlogController < ApplicationController

def display_by_date
 year = params[:year]
 month = params[:month]
 day = params[:day]
 day ='0'+day if day && day.size == 1
 @day = day
 if ( year && month && day )
  render(:template => "blog/#{year}/#{month}/#{day}")
 elsif ( year )
  render(:template => "blog/#{year}/list")
 end
end

end

I'm not sure what to name the templates so the router can find them. Thanks for your help.


I can imagine what's going on here, but I think the code example is way off base for a number of reasons. For one, calls to render(:template) aren't routed as they're actually file paths. What this might be doing is pulling in pre-rendered pages and wrapping them in the application layout as some kind of rudimentary caching. It is not clear what is generating these cached files in the first place.

You would need to have files along the lines of:

app/views/blog/2010/10/20.html.erb
app/views/blog/2010/list.html.erb

Routes are what delegate incoming requests to the appropriate controller action, so those are likely something along the lines of this:

map.connect '/blog/:year/list', :controller => 'blog', :action => 'display_by_date'
map.connect '/blog/:year/:month/:day', :controller => 'blog', :action => 'display_by_date'

What you should do instead of this kind of template-cache-delegation is make use of the Rails.cache mechanism which supports many ways of saving partial results, including files, but with a much more reasonable way of generating and expiring them.

As a note, that's some atrocious formatting code. Typically you'd format parameters using a simple method like:

render(:template => "blog/%04d/%02d/%02d" % [ params[:year].to_i, params[:month].to_i, params[:day].to_i ])

This will pad with zeroes as required. This is considerably more robust than checking the length of your string, and adding a zero if it is only one and has the advantage of being only a single line that defines your format and template in one.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号