def get_template(file):
    ''' Lookup a template class for the given filename or file
        extension. Return nil when no implementation is found.
    '''

    pattern = str(file).lower()
    while len(pattern) and not Lean.is_registered(pattern):
      pattern = os.path.basename(pattern)
      pattern = re.sub(r'^[^.]*\.?','',pattern)

  	# Try to find a preferred engine.
    preferred_klass = Lean.preferred_mappings[pattern] if Lean.preferred_mappings.has_key(pattern) else None

    if preferred_klass:
  		return preferred_klass

  	# Fall back to the general list of mappings
    klasses = Lean.template_mappings[pattern]

  	# Try to find an engine which is already loaded
    template = None
    for klass in klasses:
  		if hasattr(klass,'is_engine_initialized') and callable(klass.is_engine_initialized):
  			if klass.is_engine_initialized():
  				template = klass
  				break

 		if template:
 			return template

 		# Try each of the classes until one succeeds. If all of them fails,
   	# we'll raise the error of the first class.
    first_failure = None

    for klass in klasses:
      try:
        return klass
      except Exception, e:
        if not first_failure:
          first_failure = e

   	if first_failure:
   		raise Exception(first_failure)
Lookup a template class for the given filename or file
        extension. Return nil when no implementation is found.