/README.md

https://github.com/ubermajestix/handlebars_routes · Markdown · 88 lines · 61 code · 27 blank · 0 comment · 0 complexity · 733c07a22aa64e6f24f811d72edbac42 MD5 · raw file

  1. Handlebars Routes
  2. =================
  3. :microscope: **This was an experiment** to see if I could translate Rails routes into something useable on the client side.
  4. Its totally do-able but there are some major security implications to exposing ALL of your routes client side.
  5. I'm no longer using this library, so hopefully it will serve as inspiration to someone else.
  6. Installing
  7. ----------
  8. Bundle it
  9. gem 'handlebars_routes', '~> 0.0.1'
  10. Sprockets require it (in app/assets/javascripts/application.(js|coffee) for example):
  11. //= handlebars_routes
  12. The `link_to` helper uses [underscore.js](https://github.com/rweng/underscore-rails) templating and assumes you have put it into "mustache mode"
  13. # Setup underscore's templating to use Mustache style templates
  14. _.templateSettings =
  15. interpolate: /\{\{(.+?)\}\}/g
  16. What it does
  17. ------------
  18. Its really annoying not to have all your Rails routes on the client side especially when you're doing Javascript
  19. templating. This gem aims to fix that by dumping your rails routes into a `rails_routes` object in javascript.
  20. I've added my Handlebars Helpers `router` and `link_to`. The `link_to` helper uses the `router` helper to create
  21. links in Handlebars templates very much like creating links in Rails templates.
  22. The `router` will traverse your object looking for the right attributes to put into the route. You could also use
  23. these routes in Backbone models' urls, haven't tried it yet but its a thought.
  24. Examples are probably better eh?
  25. --------------------------------
  26. Given the Rails routes:
  27. resources :items do
  28. resources :products
  29. end
  30. Given the data (a Backbone like object):
  31. item = { attributes: {
  32. id: 42,
  33. product: {id:24, title: 'Pugs not Drugs'},
  34. item_code: "PUGS",
  35. created_at:'11/11/2011'
  36. }
  37. }
  38. And the template item/show.jst.hbs (notice the **triple-stache** around link_to).
  39. `"item_product"` is the route that Rails provided. The list of routes
  40. are stored in the `rails_routes` global javascript object. Take a look at
  41. it in Inspector to find specific routes.
  42. <tr>
  43. {{#attributes}}
  44. <td>{{{link_to product.title "item_product"}}}</td>
  45. <td> {{item_code}} </td>
  46. <td> {{created_at}}</td>
  47. {{/attributes}}
  48. </tr>
  49. And this coffeescript Backbone View:
  50. class ItemView extends Backbone.View
  51. # ...
  52. render: =>
  53. $(@el).prepend JST['item/show'] @model
  54. # ...
  55. end
  56. This awesome looking html will be produced!!!
  57. <tr>
  58. <td><a href="/items/42/products/24">Pugs not Drugs</a</td>
  59. <td>PUGS</td>
  60. <td>11/11/2011</td>
  61. </tr>