0

I just started pyramid and have a problem with loading views. I want to load a view based on a variable fetched from the database like my PHP solution here: rewrite url with htaccess

I've build a script that can do this, but I'm quite sure this is not the right way to do it. I think when I use this in a real site it will get very complicated and messy. Could someone explain how to this properly or point me to an other solution?

My current script:

config.add_route('home', '/')
config.add_route('admin_home', '/admin')
config.add_route('admin_pages', '/admin/pages')
config.add_static_view(name='static', path='website:static')

config.add_route('view_loader', '/*url')

views.py

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

    @view_config(route_name="view_loader", renderer="templates/view_loader.pt")
    def view_loader(self):
        request = self.request
        url = "/%s" % request.matchdict["url"]
        page = DBSession.query(Pages).filter_by(url=url).one()
        return dict(title=page.title, include=page.template)

view_loader.pt

<!DOCTYPE html>
<html>
<body>
    <metal:main use-macro="load: ${include}"></metal:main>
</body>
</html>

Idea of the system:

Admins can create pages in a cms with random url's and have to select a template. The system has to generate these pages.

  • url = /random/random -> look for template in db -> render template_1
  • url = /random2/random2 -> look for template in db -> render template_2

So I want to render the template after the class/method is being called to determine what template has to be rendered

Community
  • 1
  • 1
Jab
  • 791
  • 3
  • 12
  • 26
  • Instead of returning the dict() could you instead do something like `return HTTPFound(request.route_url(page.route_name))` ? – Peter Tirrell Oct 10 '13 at 18:43
  • Thanks for your response, but if i understand it right, the url will change and thats not what I mean. I'll try to clearify my question. – Jab Oct 10 '13 at 19:03
  • You can always call another method from your view; `if sometest: return otherview(request)`. – Martijn Pieters Oct 10 '13 at 21:59

1 Answers1

0

I found a more logical approach for my problem with the help of this question Map different URLs to same view. Actually the solution is quite simple I just didn't know it is possible to declare a renderer in add_view()

main.py

pages = DBSession.query(Pages)
for page in pages:
    config.add_route(str(page.name), page.url)
    if page.template.decode('utf-8') == "home_view":
        config.add_view(home_view, route_name=str(page.name), renderer='templates/home.pt')        
    elif page.template.decode('utf-8') == "detail_view":
        config.add_view(home_view, route_name=str(page.name), renderer='templates/detail.pt')    

views.py

def home_view(self, request):
    return dict(.....)
Community
  • 1
  • 1
Jab
  • 791
  • 3
  • 12
  • 26