BigBoy1337
BigBoy1337

Reputation: 4963

How can I write a view callable that displays static html files in pyramid?

In my pyramid app, I have several static html files under tutorial/tutorial/pages/name.html (for example). How can I write a view callable for this? Would this work?

     @view_config(renderer='view_page')
     def view_page(request):
         return {} # no values have to be passed to the template

then in the init.py file

config.add_route('view_page', 'tutorial:pages/{name}.html')

What do I need to put in the def view_page(request) function to call that name.html file specifically and then display its content?

Upvotes: 3

Views: 1379

Answers (1)

Michael Merickel
Michael Merickel

Reputation: 23331

Pyramid's static_view is a view capable of serving files from a directory. The part you really haven't explained is what the URLs are like for these static pages. For example, if they are all under a common prefix, you could use static_view (option 1). If they are not, then you have to create a view per page and serve it up directly (option 2).

option 1

url:

/foo/bar.html
/foo/baz/boo.html

static view:

config.add_static_view('/foo', 'tutorial:pages')

tutorial/pages hierarchy:

tutorial/pages/bar.html
tutorial/pages/baz/boo.html

add_static_view is effectively like calling add_route('foo', '/foo/*subpath'), and it serves up the subpath relative to tutorial:pages.

option 2

config.add_route('foo', '/foo')
config.add_route('bar', '/foo/bar')

@view_config(route_name='foo', renderer='tutorial:pages/foo.html.mako')
@view_config(route_name='bar', renderer='tutorial:pages/bar.html.mako')
def static_view(request):
    return {}

Notice the .mako suffix to invoke the mako renderer. There is no .html renderer by default, but you could make one.

Upvotes: 4

Related Questions