From Rails to Marionette.js in a few simple steps.
We will use users#show
view as an example.
Create in backbone/apps/
a new app for users
and add users_show_controller
, users_show_views
and users_app
files:
Now it is time to think- how should I divide my page? In our example, users show page has 3 regions.
So our next step is to create a layout view with 3 regions.
Add your template to show/templates
.
You can choose from different templates:
And add basic views for those regions:
Next in the controller:
We can pass region to the controller (see the previous step) or we can use
App.mainRegion
that should be defined inapp.coffee
. For example:App.addRegions({ mainRegion: "#main-region" })
.
Now we will show our empty views in proper regions
This is in some cases a hard part. Why? We need to change every helper method to a proper tag (you can check rendered HTML for a Rails view). This should be your first step - rewrite templates to a simple HTML (hbs/HAML).
A simple example:
to:
Now it's time to add some logic. A good thing with rewriting templates is that you see what kind of information you will need from server and which you can do on a client side (like text, date formatting).
In our example we will add a User
entity:
Note:
Routes
is from js-routes. You could also add a simple string or useurl
option instead ofurlRoot
.
If you have a backbone view and you use gon you could use it instead of creating an entity. You can move to step 7 if you want to stick with gon
. :warning: Be aware that it is only a temporary solution and you should replace it with an entity and API.
We can now use it in our controller:
and pass it to views:
In this step you have 2 options:
users#show
actionAPI::UsersController
To render json you can use:
Example controller + serializer:
Now we can use our user
entity in templates and add events to your views and controller. If you have an old backbone view you can move your events and other stuff to your marionette views.
There is a simple solution to replace your Rails view with Marionette view:
Add feature flag for your new page - you can use flip or something else. We will use backbone_users_show
flag:
Next add if/else
to your Rails view:
and to users_app.coffee
:
Vilà!