import django.shortcuts
from django.http import HttpResponse
from django.template import loader
from django.template.context import Context

template_cache = { }
def render_to_response(*args, **kwargs) :
  """Implement two changes relative to django.shortcuts.render_to_response:
       1) Use content-type 'application/xhtml+xml' if supported by the client.
       2) Cache the compiled template.
  """

  # Set content type to application/xhtml+xml if conditions allow.
  if not kwargs.has_key('mimetype') and \
     kwargs.has_key('context_instance') and \
     kwargs['context_instance'].has_key('request') and \
     kwargs['context_instance']['request'].META.has_key('HTTP_ACCEPT') and \
     'application/xhtml+xml' in \
       kwargs['context_instance']['request'].META['HTTP_ACCEPT'].split(',') :
    kwargs['mimetype'] = 'application/xhtml+xml'

  # Load template (use cache if possible).
  template_path = args[0]
  if template_cache.has_key(template_path) :
    template = template_cache[template_path]
  else :
    template = loader.get_template(template_path)
    template_cache[template_path] = template

  # Render template using provided context.
  if kwargs.has_key('context_instance') :
    context_instance = kwargs['context_instance']
  else :
    context_instance = Context()

  if len(args) > 1 :
    context_instance.update(args[1])

  rendering = template.render(context_instance)

  # Return HttpResponse using rendered template.
  httpresponse_kwargs = {'mimetype': kwargs.pop('mimetype', None)}
  return HttpResponse(rendering, **httpresponse_kwargs)