python - In Pyramid, how can I use a different renderer based on contents of context? -


i have 3 different product page layouts display dependent on information available products. using traversal have class called productfinder grabs information. example user goes domain/green/small , productfinder list products db green , small. list self.products in productfinder class. in __init__.py have added line:

config.add_view('app.views.products', name='') 

in products.py have:

from pyramid.view import view_config @view_config(context='app.models.productfinder', renderer='productpage.mako') def products(context, request):     return dict(page=context) 

based on what's in context.products though i'd render different mako. in pylons have done like:

def products(context, request):     if len(context.products) == 1:         return render("oneproduct.mako")     elif len(context.product) == 2:         return render("twoproducts.mako") 

so how can render different template based on contents of context?

i start off saying sort of seems want take care of in template.

however, can influence renderer used part of view lookup in way want to. might know can use same view handler multiple views, need pyramid figure out 1 use.

for example:

from pyramid.view import view_config  def productlengthpredicate(length):     def check_length(context, request):         return len(context.products) == length     return check_length  @view_config(context='app.models.productfinder', renderer='oneproduct.mako',              custom_predicates=(productlengthpredicate(1),)) @view_config(context='app.models.productfinder', renderer='twoproducts.mako',              custom_predicates=(productlengthpredicate(2),)) @view_config(context='app.models.productfinder', renderer='manyproducts.mako') def products(context, request):     return dict(page=context) 

nb. people might more interested in render_to_response approach here because not relying on custom_predicates. of course you!

@view_config(context='app.models.productfinder', renderer='manyproducts.mako') def products(context, request)     opts = dict(page=context)     if len(context.products) == 1:         return render_to_response('oneproduct.mako', opts, request)     if len(context.products) == 2:         return render_to_response('twoproducts.mako', opts, request)     return opts 

this works because pyramid ignore renderers if view returns response() render_to_response does.


Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -