Search code examples
javascriptpythonember.jsurl-routingpyramid

Routing an SPA with pyramid and ember.js


I am developing a SPA (Single page application) using ember.js served from pyramid. The problem is that the routing is not working properly.

In pyramid, I have the following routes defined:

# Route to index.html, i.e. the SPA
config.add_route('index', '/')
# Route to css & js resources
config.add_static_view('', 'myapp:static')

And the index view is:

@view_config(route_name='index')
def index_view(request):
    with open('myapp/templates/index.html', 'rt', encoding='utf-8') as fh:
        html = fh.read()
    return Response(html, content_type='text/html')

Here is my index.html:

<!DOCTYPE html>
<html>
  <head>
    <title>Test</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="libs/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  </head>
  <body>
    <h1>Hello, world!</h1>
    <script type="text/x-handlebars" data-template-name="wfw">
      <section id="wfw">
        <p>here is a page</p>
      </section>
    </script>

    <script src="js/application.js"></script>
    <script src="js/router.js"></script>

    <script src="https://code.jquery.com/jquery.js"></script>
    <script src="http://builds.emberjs.com/release/ember.js"></script>
    <script src="http://builds.handlebarsjs.com.s3.amazonaws.com/handlebars-v1.3.0.js"></script>
    <script src="https://raw.github.com/less/less.js/master/dist/less-1.6.0.min.js"></script>
    <script src="libs/bootstrap/js/bootstrap.min.js"></script>
  </body>
</html>

js/application.js:

window.Wfw = Ember.Application.create();

js/router.js:

Wfw.Router.map(function () {
  this.resource('wfw', { path: '/t' });
});

When I go to localhost:6543/ I get "Hello, world!", but I don't see "here is a page". If I change the path in js/router.js to '/test' and go to localhost:6543/test, I get a 404. What am I doing wrong? Do I need to somehow disable part of pyramid's routing, or am I doing something wrong with ember?


Solution

  • A few things:

    1. I think you need to move your Ember.js script tags above your application specific tags.

    2. The path you have configured is /t so I don't think it would pick it up /test.

    3. By default, ember doesn't use the html5 history api, so your url would need to be like: localhost:6543/#/t