HTML templating library for JS
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. # Templish
  2. A templating language for JavaScript, using JavaScript.
  3. ## Installation
  4. Install with NPM:
  5. npm install --save templish
  6. ## Usage
  7. A simple example:
  8. ``` JavaScript
  9. //First, require the library
  10. var Templish = require("templish");
  11. //Create a templish template
  12. var t = new Templish("<title>{{conf.title}}</title>", ["conf"]);
  13. //Create an environment
  14. var env = {
  15. conf: {
  16. title: "Hello, World!"
  17. }
  18. }
  19. //Execute the template
  20. t.exec(env, function(err, res) {
  21. console.log(res); //<title>Hello, World!</title>
  22. });
  23. //Execute the template again, this time with a different environment
  24. env = {
  25. conf: {
  26. title: "Good Morning, Earth!"
  27. }
  28. }
  29. t.exec(env, function(err, res) {
  30. console.log(res); //<title>Good Morning, Earth!</title>
  31. });
  32. ```
  33. We can do more complex things, even with asynchronous functions:
  34. ``` JavaScript
  35. var fs = require("fs");
  36. var Templish = require("templish");
  37. //Create a templish template
  38. var t = new Templish(
  39. "<title>{{fs.readFile('someFile', 'UTF8', cb)}}</title>",
  40. ["fs"]
  41. );
  42. //Create an environment, this time with the `fs` method to let us access files
  43. var env = {
  44. fs: fs
  45. }
  46. //Execute the template
  47. t.exec(env, function(err, res) {
  48. console.log(res); //If we assume the `someFile` file contains "hi, world":
  49. //<title>hi, world</title>
  50. });
  51. ```
  52. We can have multiple statements:
  53. ``` JavaScript
  54. var Templish = require("templish");
  55. //Create a templish template
  56. var t = new Templish("\
  57. <title>{{ \
  58. var str = 'Hello World'; \
  59. return str; \
  60. }}</title>",
  61. []
  62. );
  63. //Execute the template
  64. t.exec({}, function(err, res) {
  65. console.log(res) //<title>Hello World</title>
  66. });
  67. ```
  68. Notice that with multiple statements, you have to include the `return` statement yourself.
  69. Of course, in practice, you would probably want your templates to be individual files, and not inline in the script file, not that Templish cares, as long as it receives a string.