shortcuts.py 1.97 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#   Copyright (c) 2008 Mikeal Rogers
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

from django.template import Context
from django.http import HttpResponse

18
from . import middleware
Piotr Mitros committed
19 20
from django.conf import settings

21

22 23
def render_to_string(template_name, dictionary, context=None, namespace='main'):
    context_instance = Context(dictionary)
24 25 26 27
    # add dictionary to context_instance
    context_instance.update(dictionary or {})
    # collapse context_instance to a single dictionary for mako
    context_dictionary = {}
Piotr Mitros committed
28
    context_instance['settings'] = settings
29
    context_instance['MITX_ROOT_URL'] = settings.MITX_ROOT_URL
30 31 32 33 34

    # In various testing contexts, there might not be a current request context.
    if middleware.requestcontext is not None:
        for d in middleware.requestcontext:
            context_dictionary.update(d)
35 36
    for d in context_instance:
        context_dictionary.update(d)
37
    if context:
38
        context_dictionary.update(context)
39
    # fetch and render template
40
    template = middleware.lookup[namespace].get_template(template_name)
41
    return template.render_unicode(**context_dictionary)
42

43

44
def render_to_response(template_name, dictionary, context_instance=None, namespace='main', **kwargs):
45 46 47 48
    """
    Returns a HttpResponse whose content is filled with the result of calling
    lookup.get_template(args[0]).render with the passed arguments.
    """
49
    return HttpResponse(render_to_string(template_name, dictionary, context_instance, namespace), **kwargs)