Stephen M Stephen M - 4 months ago 33
AngularJS Question

Use mezzanine together with angularjs

I'm setting up a simple website, and I wanted to integrate angularjs for the UI. However, it seems the CMS takes over everything and serves up everything, including anything I want served up through angularjs.

My urls.py file:

urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
(r'^users/', include('apps.site_users.urls')),
url('^$', 'mezzanine.pages.views.page', {'slug': '/'}, name='home'),
url('', include('social.apps.django_app.urls', namespace='social')),
('^', include('mezzanine.urls')),
)


I have all the necessary changes for angularjs to work since without the CMS, everything loads just fine, but this means I can't serve up the other pages I have in the CMS. Any ideas on what needs to be done?

Answer

You can easily setup Mezzanine to work with Angular in HTML5 Mode by setting up your app's routing on Angular and your base URLs via Django, making sure that any uncaught URL scheme redirects to the "home" URL:

On Django:

# urls.py
urlpatterns = patterns("",
    # Change the admin prefix here to use an alternate URL for the
    # admin interface, which would be marginally more secure.
    ("^admin/", include(admin.site.urls)),

    # If you'd like more granular control over the patterns in
    # ``mezzanine.urls``, go right ahead and take the parts you want
    # from it, and use them directly below instead of using
    # ``mezzanine.urls``.
    ("^", include("mezzanine.urls")),

    # AngularJS HTML5 mode (ie, remove the /#/ from URLs):
    # We need to redirect any uncaught URL schemes to the default home view.
    # http://scotch.io/quick-tips/js/angular/pretty-urls-in-angularjs-removing-the-hashtag
    url(r'^.*$', TemplateView.as_view(template_name='index.html'), name='home'),

    # etc...
)

On Angular:

// app.js
app.config(function ($routeProvider, $locationProvider) {
  $routeProvider
    .when('/', {
      templateUrl: '/static/app/views/home.html',
    })
    .when('/profile/:profileId', {
      templateUrl: '/static/app/views/profile.html',
      controller: 'ProfileCtrl'
    })
    .when('/results', {
      templateUrl: '/static/app/views/results.html',
      controller: 'ResultsCtrl'
    })
    .otherwise({
      redirectTo: '/'
    });

    $locationProvider.html5Mode(true);
  });
});

On HTML:

<!-- index.html -->
<!doctype html>
<html class="no-js" lang="es" ng-app="myApp">
  <head>
    <base href="/">
    <!-- etc -->
  </head>
  <!-- etc -->
</html>

Related blog post here.