Render HTML from Object with CoffeeKup

by Max Rohde,

CoffeeKup allows to render HTML from multiple sources:

  • A String containing valid CoffeeScript code
  • A JavaScript/CoffeeScript object arranged according to CoffeeKup rules

To render HTML from a String is quite straightforward and documented on the CoffeeeScript reference: you can use the methods .compile and .render as documented there.

However, to render HTML from a JavaScript/CoffeeScript object can also come in handy, to create a tight link between your logic and markup. The .render method is not only able to process a String but is also able to process a certain kind of Object as well.

Here find two examples of how to render JavaScript and CoffeeScript objects into HTML:

JavaScript Object

CoffeeKup.render(function () {
  return div({ class: 'mydiv' }, 'Hello World');
});

which results in:

"<div class='mydiv'>Hello World</div>"

CoffeeScript Object

CoffeeKup.render(div 'mydiv', ->'Hello World'<span style="line-height: 1.5em;">);

resulting in the same HTML as above.

Categories: javascript