Skip to content

Instantly share code, notes, and snippets.

@denkiryokuhatsuden
Created November 18, 2014 04:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save denkiryokuhatsuden/93093f78f5c1381cf3a3 to your computer and use it in GitHub Desktop.
Save denkiryokuhatsuden/93093f78f5c1381cf3a3 to your computer and use it in GitHub Desktop.
[THIS DOES NOT WORK AT ALL] Simpler named routing feature for express.
...
# before any routing requirings
require './router'
routes = require './routes/index'
...
express = require('express')
router = express.Router()
router.route '/'
.bind 'index'
.get (req, res) ->
res.render 'index', { title: "named routing" }
router.route '/about/:what'
.bind 'about'
.get (req, res) ->
res.render 'about', { what: what }
extends layout
block content
h1= title
ul
li
a(href=url('about', { what: 'me' })) about me
li
a(href=url('about', { what: 'company' })) about company
###
inspired from https://github.com/silexphp/Silex
put this file onto your preferred place and just require.
###
express = require 'express'
routes = []
###
bind() enables you to name the route
example
router.route '/'
.bind 'your-route-name'
.get blah-blah
.post blah-blah
###
express.Route.prototype.bind = (name) ->
console.log "#{@path} bound to #{name}"
routes[name] = @
module.exports = (req, res, next) ->
###
helper url() enables you to generate url related to name that you once specified using bind()
###
res.locals.url = (name, param = {}) ->
route = routes[name] || { path: "##undefined route:#{name}" }
pattern = route.path
chunks = pattern.split '/'
requiredParams = []
for c in chunks when c.charAt(0) == ':' then requiredParams.push c.slice 1
for r in requiredParams
return "##parameter not satisfied: #{r}" unless r
p = param[r]
pattern = pattern.replace ":#{r}", p
req.baseUrl + pattern
next()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment