docpad

How to setup docpad.coffee helper functions for collection generation?


For collections I'd like to use helpers defined within docpad.coffee such as

getLang: (inLang) ->
    "/" + inLang  + "/"
...
myCollection: ->
        @getCollection("html").findAllLive().on "add", (model) ->
           model.setMeta({ url: @getLang("en") + defaultUrlPartGoesHere })

but can't get the FilesCollection to know my helper :/

How to setup helper functions to become available for collection definition?


Solution

  • Referencing docpadConfig.templatedata.getLang() will work, but if you find that distasteful, remember that docpad.coffee is just a standard NodeJS module (written in coffeescript). You could also define your function outside of the docpadConfig literal object and then both pull it into your templateData (assuming you need it for templates) and use it when building your collection.

    For example:

    # define the function outside of the config object
    getLang: (inLang) ->
        "/" + inLang  + "/"
    
    docpadConfig = {
        templateData:
            getLang: getLang # reference the previously defined function
    
        collections:
            myCollection: ->
                # use the previously defined function
                @getCollection("html").findAllLive().on "add", (model) ->
                    model.setMeta({ url: getLang("en") + defaultUrlPartGoesHere })  
    }