{"id":17482441,"url":"https://github.com/creationix/grain","last_synced_at":"2025-04-10T02:44:11.477Z","repository":{"id":57253036,"uuid":"451419","full_name":"creationix/grain","owner":"creationix","description":"Grain is an async framework for node-js templating languages. ","archived":false,"fork":false,"pushed_at":"2011-12-03T15:09:01.000Z","size":346,"stargazers_count":28,"open_issues_count":1,"forks_count":1,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-24T04:14:42.589Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/creationix.png","metadata":{"files":{"readme":"README.markdown","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2009-12-28T20:38:37.000Z","updated_at":"2023-09-08T16:26:08.000Z","dependencies_parsed_at":"2022-08-31T22:11:44.151Z","dependency_job_id":null,"html_url":"https://github.com/creationix/grain","commit_stats":null,"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/creationix%2Fgrain","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/creationix%2Fgrain/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/creationix%2Fgrain/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/creationix%2Fgrain/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/creationix","download_url":"https://codeload.github.com/creationix/grain/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248145644,"owners_count":21055175,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-18T23:43:31.588Z","updated_at":"2025-04-10T02:44:11.451Z","avatar_url":"https://github.com/creationix.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Grain Templating System\n\nAll template languages have 5 parts in common.\n\n - Static content\n - Parameters\n - Dynamic content\n - Loops/Conditionals\n - Asynchronous parts\n\nOk, maybe the last one isn't that common, but in a NodeJS world where nothing blocks it's required for many use cases.  Partial templates require usually that another external resource get loaded and compiled.  If this resource is loaded over some IO then it's an asynchronous operation.  Also it would be nice to be able to stream content to the browser as information is known.\n\nGrain is both a spec for interfaces between template languages and a helper library to help write compilers that follow the spec.  Included is a sample template language called `Corn` that implements the spec using `grain`.\n\n## Inversion of control\n\nOne way to handle the async nature of retrieving data is to pre-calculate all the data that's needed for a template to render, and then as the last step pass it to the template function which returns the output text in a single sync function call.  This works and is very simple from the point of view of the author of the template language, but it's a lot of burden on the person using the template language.\n\nMy proposed method is to pass the template function an hash of values and data providing functions.  The template language will call the data providers as it needs data.  If they are async functions, then it will hold that place in the template and defer rendering of that part till the callback comes back with the data.  Then the template will output it's result after the pending function calls have finished.\n\n## Template language compiler module interface\n\nAll grain engines need to comply with this simple interface to allow interoperability between frameworks and projects.\n\n### Compiler\n\nThe module itself is a function that takes in template source code as text and returns compiled function that renders that template on demand.\n\n    function compile(text) -\u003e function fn(locals, callback|stream)\n    module.exports = compile\n\nThe returned function accepts two arguments, they are `locals` and then either a `callback` function or a `stream` instance.  The properties of `locals` are available within the template as local variables, usually using `with`.\n\n### Callback\n\nIf a callback is provided it's interface will be:\n\n    function callback(err, result) { ... }\n\nWhere `err` will contain an instance of `Error` if an exception happens while rendering, otherwise, `err` will be falsy and result will contain the final output of the entire template.\n\n### Stream\n\nIf a stream if given instead, it will `emit(\"data\", chunk)` as chunks of output are finished.  It will `emit('end')` when done, and `emit('error', err)` where there is an exception.\n\n### Currying\n\nThe compile function will act as if it's a curried function and accept the locals and callback|stream parameters directly.\n\n    function callback(text, locals, callback|stream)\n\n### Helpers\n\nThe module itself will also have a `helpers` object that gets mixed into every locals parameter.  A simple way to implement this is on the first line of the generated code in `fn` do:\n\n    locals.__proto__ = module.exports.helpers;\n\n## Sample code\n\nSuppose this simple template language where `@foo` is the variable `foo` and `@bar()` calls the data provider `bar()` and inserts the result inline.\n\nI would require my compiler like this (corn is included as a sample):\n\n    var compiler = require('grain/corn');\n\nNow let's suppose this simple template:\n\n    var template = \"Hello @planet, my name is @name() and I am @age() years old.\";\n\nWith this sample data:\n\n    var data = {\n      // Value\n      planet: \"world\",\n      // Async getter\n      name: function name(callback) {\n        process.nextTick(function () {\n          callback(null, \"Tim Caswell\");\n        });\n      },\n      // sync getter\n      age: function age() {\n        return 28;\n      }\n    };\n\nTo compile the template it's simply:\n\n    var fn = compiler(template);\n\nAnd then to render it do:\n\n    fn(data, function (err, text) {\n      if (err) {\n        console.log(\"ERROR \" + err.stack);\n        return;\n      }\n      console.log(\"OUTPUT \" + text);\n    });\n\nOr to render with a stream:\n\n    var stream = new process.EventEmitter();\n    fn(data, stream);\n    stream.addListener('data', function (data) {\n      console.log(\"DATA \" + JSON.stringify(data.toString()));\n    });\n    stream.addListener('end', function () {\n      console.log(\"END\");\n    });\n    stream.addListener('error', function (err) {\n      console.log(\"ERROR \" + err.stack);\n    });\n\nAlso you can compile and render it in one shot:\n  \n    compiler(template, data, callback);\n\nIf I wanted a helper that did partials, I would add it like this:\n\n    var fs = require('fs');\n    compiler.helpers = {\n      partial: function (filename, data, callback) {\n        fs.readFile(filename, 'utf8', function (err, text) {\n          if (err) { callback(err); return; }\n          compiler(text, data, callback);\n        });\n      }\n    }\n\nAnd then it would be available within the template as `partial()` without me having to pass it into the data hash every time.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcreationix%2Fgrain","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcreationix%2Fgrain","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcreationix%2Fgrain/lists"}