Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
###
# Below is a quick example of how CoffeeScript can be used to easily template JSON
#
# CoffeeScript has a few notable features for this role:
#
# 1. It has existential accessors, so you safely invoke nested properties w/o checking for their existence explicitly (`myObj.someOptionalProp?.someOtherOptProp?.val)
# 2. Using the "do" constrution you can execute anonymous functions that return objects in place, allowing fairly straightforward conditional json properties and other pre-processing.
# 3. Using multi-line object definitions and the underscore extend method, it's fairly literate to intermingle code with basic json values.
# 4. It's object notation is nice.
###
module.export = (locals) ->
_({}).extend
a: 3
b: 2
,
do () ->
if locals.someProp
somePropMappedKey: locals.someProp
,
objProp:
_({}).extend
d: locals.d
, do () ->
if locals.someObj?.nestedProp
nestedProp: locals.someObj?.nestedProp
aryProp: do () ->
prop.key for prop in locals.someArrayOfObjects
###
# This should result in an object like this:
#
# {
# a: 3,
# b: 2,
# somePropMappedKey: "value of locals.someProp",
# objProp: {
# d: "value of locals.d",
# nestedProp: "value of someObj"
# },
# aryProp: [ "prop.key val 1", "prop.key val 2"]
# }
#
# This can then be run with code like this:
#
# template = require './templates/my-template'
# res.send template(locals)
#
# That code could be further exposed via a middleware-injected function res.renderJSON
###
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment