1
0
Fork 0
mirror of https://github.com/sinatra/sinatra synced 2023-03-27 23:18:01 -04:00

extract template lookup logic, fixes #48

This commit is contained in:
Konstantin Haase 2011-02-19 15:37:49 +01:00
parent 79c5acc5a7
commit 441b17ead9
4 changed files with 36 additions and 4 deletions

View file

@ -460,6 +460,15 @@ module Sinatra
render :slim, template, options, locals
end
# Calls the given block for every possible template file in views,
# named name.ext, where ext is registered on engine.
def find_template(views, name, engine)
Tilt.mappings.each do |ext, klass|
next unless klass == engine
yield ::File.join(views, "#{name}.#{ext}")
end
end
private
# logic shared between builder and nokogiri
def render_ruby(engine, template, options={}, locals={}, &block)
@ -516,10 +525,12 @@ module Sinatra
template.new(path, line.to_i, options) { body }
else
found = false
Tilt.mappings.each do |ext, klass|
next unless klass == template
path = ::File.join(views, "#{data}.#{ext}")
break if found = File.exists?(path)
find_template(views, data, template) do |file|
path ||= file # keep the initial path rather than the last one
if found = File.exists?(file)
path = file
break
end
end
throw :layout_missing if eat_errors and not found
template.new(path, 1, options)

View file

@ -247,6 +247,25 @@ class TemplatesTest < Test::Unit::TestCase
assert ok?
assert_equal 'Hello World!', body
end
it "is possible to use custom logic for finding template files" do
mock_app do
set :views, ["a", "b"].map { |d| File.dirname(__FILE__) + '/views/' + d }
def find_template(views, name, engine, &block)
Array(views).each { |v| super(v, name, engine, &block) }
end
get('/:name') do
render :str, params[:name].to_sym
end
end
get '/in_a'
assert_body 'Gimme an A!'
get '/in_b'
assert_body 'Gimme a B!'
end
end
# __END__ : this is not the real end of the script.

1
test/views/a/in_a.str Normal file
View file

@ -0,0 +1 @@
Gimme an A!

1
test/views/b/in_b.str Normal file
View file

@ -0,0 +1 @@
Gimme a B!