template.py 2.55 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   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.

15 16
import edxmako

17
from django.conf import settings
18
from edxmako.middleware import get_template_request_context
David Baumgold committed
19
from edxmako.shortcuts import marketing_link
20
from mako.template import Template as MakoTemplate
21

22
DJANGO_VARIABLES = ['output_encoding', 'encoding_errors']
23

24
# TODO: We should make this a Django Template subclass that simply has the MakoTemplate inside of it? (Intead of inheriting from MakoTemplate)
Calen Pennington committed
25 26


27
class Template(MakoTemplate):
28 29 30 31 32
    """
    This bridges the gap between a Mako template and a djano template. It can
    be rendered like it is a django template because the arguments are transformed
    in a way that MakoTemplate can understand.
    """
Calen Pennington committed
33

34 35 36
    def __init__(self, *args, **kwargs):
        """Overrides base __init__ to provide django variable overrides"""
        if not kwargs.get('no_django', False):
37 38
            overrides = {k: getattr(edxmako, k, None) for k in DJANGO_VARIABLES}
            overrides['lookup'] = edxmako.LOOKUP['main']
39
            kwargs.update(overrides)
40
        super(Template, self).__init__(*args, **kwargs)
Calen Pennington committed
41

42 43 44 45 46 47 48
    def render(self, context_instance):
        """
        This takes a render call with a context (from Django) and translates
        it to a render call on the mako template.
        """
        # collapse context_instance to a single dictionary for mako
        context_dictionary = {}
Calen Pennington committed
49

50
        # In various testing contexts, there might not be a current request context.
51 52 53 54 55 56
        request_context = get_template_request_context()
        if request_context:
            for item in request_context:
                context_dictionary.update(item)
        for item in context_instance:
            context_dictionary.update(item)
57
        context_dictionary['settings'] = settings
58
        context_dictionary['EDX_ROOT_URL'] = settings.EDX_ROOT_URL
59
        context_dictionary['django_context'] = context_instance
60
        context_dictionary['marketing_link'] = marketing_link
Calen Pennington committed
61

62
        return super(Template, self).render_unicode(**context_dictionary)