Frage

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.

War es hilfreich?

Lösung

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)}"/>

Andere Tipps

We did a pretty sizable refactor and the above code is working again. I'm guessing the context passed in wasn't initialized or there was a syntax error in one of the templates.

As an aside, the request object has a property called is_xhr which is true if the request is asynchronous. We're using this property to determine if we need to load the full page or not. So is_page = self.request.is_xhr is False

I am not sure whether this works or not

 %if not request.is_xhr:
 <inherit file='base.mako'/>
 %endif

Aassuming request is available in context

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top