Search code examples
pythondjango-templatespyramidmako

Mako Dynamic Template Inheritance


We had this code and it worked fine. After doing a refactor, it doesn't work anymore. Like the comment says, we only want to inherit from a base page if the request isn't an ajax request. To do this, we pass a parameter to the template, and, based on the parameter, we inherit or not.

View.py

class Router(object):
    def __init__(self, request):
        self.request = request

    @view_config(route_name="home")
    def get(self):
        template = "home.mak"
        value = {'isPage':self.request.is_xhr is False}
        return render_to_response(template, value, request=self.request)

Template.mak

##conditional to determine with the template should inherit from the base page
##it shouldn't inherit from the base page is it is being inserted into the page using ajax
<%!

   def inherit(context):
       if context.get('isPage') == True:
           return "base.mak"
       else:
           return None
%>
<%inherit file="${inherit(context)}"/>

Currently, the error is Undefined does not have attribute __getitem__. If we change ${inherit(context)} to ${inherit(value)} we get global variable value is undefined.


Solution

  • Just ran into the same problem, same use case as well actually (render layout or not depending the request being an XHR).

    You can apparently access the request through context, so you can avoid having to split this tiny bit of logic over two places (view and template):

    <%!
       def inherit( context ):
           if not context.get('request').is_xhr:
               return 'layout_reports.mako'
           else:
               return None
    %>
    <%inherit file="${inherit(context)}"/>