Skip to content

Using Coffeescript in Slm (with ExpressJS)

Joshua Davison edited this page Jan 12, 2016 · 1 revision

Using Coffeescript in Slm (with ExpressJS)

Prerequisites:

You need to have installed slm and coffee-script to your node_modules directory.

npm install slm --save
npm install coffee-script --save

Usage

As per the Slm README.md, you should have added the following to your app.js file:

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'slm');

You should now copy the following code to the area immediately before the above code.

app.engine('slm', function(path, options, fn) {
  slm = require('slm');
  coffee = require('coffee-script');
  slm.template.registerEmbeddedFunction('coffee', function (text) {
    output = coffee.compile(text);
    return '<script type="text/javascript">' + output + '</script>';
  });
  return slm.__express(path, options, fn);
});

This wrapper calls coffee.compile() on blocks that are marked with coffee:

Example

doctype html
html
  head
    title Slm w/Coffee!
    coffee:
      alert 'Congratulations! Your coffee has been delivered.'
      # Of course, you can use coffee-script comments that won't be shown to the browser.
  body
    h1 Slm with CoffeeScript
    p You should have noticed an alert as the page loaded. If you didn't, something probably broke.

Notes

I haven't added a try and catch block, as I personally let the errors throw and handle them with other ExpressJS middleware.

Credits

Joshua 'JD' Davison - github.com/ozjd