| TOPOBJECT | = | defined?(BasicObject) ? BasicObject : Object |
| VERSION | = | '1.3' |
Lookup a template class for the given filename or file extension. Return nil when no implementation is found.
# File lib/tilt.rb, line 71
71: def self.[](file)
72: pattern = file.to_s.downcase
73: until pattern.empty? || registered?(pattern)
74: pattern = File.basename(pattern)
75: pattern.sub!(/^[^.]*\.?/, '')
76: end
77:
78: # Try to find a preferred engine.
79: klass = @preferred_mappings[pattern]
80: return klass if klass
81:
82: # Fall back to the general list of mappings.
83: klasses = @template_mappings[pattern]
84:
85: # Try to find an engine which is already loaded.
86: template = klasses.detect do |klass|
87: if klass.respond_to?(:engine_initialized?)
88: klass.engine_initialized?
89: end
90: end
91:
92: return template if template
93:
94: # Try each of the classes until one succeeds. If all of them fails,
95: # we'll raise the error of the first class.
96: first_failure = nil
97:
98: klasses.each do |klass|
99: begin
100: klass.new { '' }
101: rescue Exception => ex
102: first_failure ||= ex
103: next
104: else
105: return klass
106: end
107: end
108:
109: raise first_failure if first_failure
110: end
Create a new template for the given file using the file‘s extension to determine the the template mapping.
# File lib/tilt.rb, line 61
61: def self.new(file, line=nil, options={}, &block)
62: if template_class = self[file]
63: template_class.new(file, line, options, &block)
64: else
65: fail "No template engine registered for #{File.basename(file)}"
66: end
67: end
# File lib/tilt.rb, line 12
12: def self.normalize(ext)
13: ext.to_s.downcase.sub(/^\./, '')
14: end
Makes a template class preferred for the given file extensions. If you don‘t provide any extensions, it will be preferred for all its already registered extensions:
# Prefer RDiscount for its registered file extensions: Tilt.prefer(Tilt::RDiscountTemplate) # Prefer RDiscount only for the .md extensions: Tilt.prefer(Tilt::RDiscountTemplate, '.md')
# File lib/tilt.rb, line 40
40: def self.prefer(template_class, *extensions)
41: if extensions.empty?
42: mappings.each do |ext, klasses|
43: @preferred_mappings[ext] = template_class if klasses.include? template_class
44: end
45: else
46: extensions.each do |ext|
47: ext = normalize(ext)
48: register(template_class, ext)
49: @preferred_mappings[ext] = template_class
50: end
51: end
52: end
Register a template implementation by file extension.
# File lib/tilt.rb, line 17
17: def self.register(template_class, *extensions)
18: if template_class.respond_to?(:to_str)
19: # Support register(ext, template_class) too
20: ext = template_class
21: template_class = extensions[0]
22: extensions = [ext]
23: end
24:
25: extensions.each do |ext|
26: ext = normalize(ext)
27: mappings[ext].unshift(template_class).uniq!
28: end
29: end