{"id":13596334,"url":"https://github.com/blueimp/JavaScript-Templates","last_synced_at":"2025-04-09T16:32:19.922Z","repository":{"id":43270018,"uuid":"2955224","full_name":"blueimp/JavaScript-Templates","owner":"blueimp","description":"1KB lightweight, fast \u0026 powerful JavaScript templating engine with zero dependencies. Compatible with server-side environments like node.js, module loaders like RequireJS and all web browsers.","archived":true,"fork":false,"pushed_at":"2021-09-25T15:04:10.000Z","size":960,"stargazers_count":1723,"open_issues_count":1,"forks_count":661,"subscribers_count":111,"default_branch":"master","last_synced_at":"2024-10-30T01:48:46.675Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://blueimp.github.io/JavaScript-Templates/","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/blueimp.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null},"funding":{"github":["blueimp"]}},"created_at":"2011-12-10T20:55:40.000Z","updated_at":"2024-10-23T17:19:52.000Z","dependencies_parsed_at":"2022-07-09T16:16:54.130Z","dependency_job_id":null,"html_url":"https://github.com/blueimp/JavaScript-Templates","commit_stats":null,"previous_names":[],"tags_count":38,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/blueimp%2FJavaScript-Templates","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/blueimp%2FJavaScript-Templates/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/blueimp%2FJavaScript-Templates/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/blueimp%2FJavaScript-Templates/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/blueimp","download_url":"https://codeload.github.com/blueimp/JavaScript-Templates/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245078201,"owners_count":20557284,"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-08-01T16:02:19.243Z","updated_at":"2025-04-09T16:32:14.913Z","avatar_url":"https://github.com/blueimp.png","language":"JavaScript","readme":"# JavaScript Templates\n\n## Contents\n\n- [Demo](https://blueimp.github.io/JavaScript-Templates/)\n- [Description](#description)\n- [Usage](#usage)\n  - [Client-side](#client-side)\n  - [Server-side](#server-side)\n- [Requirements](#requirements)\n- [API](#api)\n  - [tmpl() function](#tmpl-function)\n  - [Templates cache](#templates-cache)\n  - [Output encoding](#output-encoding)\n  - [Local helper variables](#local-helper-variables)\n  - [Template function argument](#template-function-argument)\n  - [Template parsing](#template-parsing)\n- [Templates syntax](#templates-syntax)\n  - [Interpolation](#interpolation)\n  - [Evaluation](#evaluation)\n- [Compiled templates](#compiled-templates)\n- [Tests](#tests)\n- [License](#license)\n\n## Description\n\n1KB lightweight, fast \u0026 powerful JavaScript templating engine with zero\ndependencies.  \nCompatible with server-side environments like [Node.js](https://nodejs.org/),\nmodule loaders like [RequireJS](https://requirejs.org/) or\n[webpack](https://webpack.js.org/) and all web browsers.\n\n## Usage\n\n### Client-side\n\nInstall the **blueimp-tmpl** package with [NPM](https://www.npmjs.org/):\n\n```sh\nnpm install blueimp-tmpl\n```\n\nInclude the (minified) JavaScript Templates script in your HTML markup:\n\n```html\n\u003cscript src=\"js/tmpl.min.js\"\u003e\u003c/script\u003e\n```\n\nAdd a script section with type **\"text/x-tmpl\"**, a unique **id** property and\nyour template definition as content:\n\n```html\n\u003cscript type=\"text/x-tmpl\" id=\"tmpl-demo\"\u003e\n  \u003ch3\u003e{%=o.title%}\u003c/h3\u003e\n  \u003cp\u003eReleased under the\n  \u003ca href=\"{%=o.license.url%}\"\u003e{%=o.license.name%}\u003c/a\u003e.\u003c/p\u003e\n  \u003ch4\u003eFeatures\u003c/h4\u003e\n  \u003cul\u003e\n  {% for (var i=0; i\u003co.features.length; i++) { %}\n      \u003cli\u003e{%=o.features[i]%}\u003c/li\u003e\n  {% } %}\n  \u003c/ul\u003e\n\u003c/script\u003e\n```\n\n**\"o\"** (the lowercase letter) is a reference to the data parameter of the\ntemplate function (see the API section on how to modify this identifier).\n\nIn your application code, create a JavaScript object to use as data for the\ntemplate:\n\n```js\nvar data = {\n  title: 'JavaScript Templates',\n  license: {\n    name: 'MIT license',\n    url: 'https://opensource.org/licenses/MIT'\n  },\n  features: ['lightweight \u0026 fast', 'powerful', 'zero dependencies']\n}\n```\n\nIn a real application, this data could be the result of retrieving a\n[JSON](https://json.org/) resource.\n\nRender the result by calling the **tmpl()** method with the id of the template\nand the data object as arguments:\n\n```js\ndocument.getElementById('result').innerHTML = tmpl('tmpl-demo', data)\n```\n\n### Server-side\n\nThe following is an example how to use the JavaScript Templates engine on the\nserver-side with [Node.js](https://nodejs.org/).\n\nInstall the **blueimp-tmpl** package with [NPM](https://www.npmjs.org/):\n\n```sh\nnpm install blueimp-tmpl\n```\n\nAdd a file **template.html** with the following content:\n\n```html\n\u003c!DOCTYPE HTML\u003e\n\u003ctitle\u003e{%=o.title%}\u003c/title\u003e\n\u003ch3\u003e\u003ca href=\"{%=o.url%}\"\u003e{%=o.title%}\u003c/a\u003e\u003c/h3\u003e\n\u003ch4\u003eFeatures\u003c/h4\u003e\n\u003cul\u003e\n{% for (var i=0; i\u003co.features.length; i++) { %}\n    \u003cli\u003e{%=o.features[i]%}\u003c/li\u003e\n{% } %}\n\u003c/ul\u003e\n```\n\nAdd a file **server.js** with the following content:\n\n```js\nrequire('http')\n  .createServer(function (req, res) {\n    var fs = require('fs'),\n      // The tmpl module exports the tmpl() function:\n      tmpl = require('./tmpl'),\n      // Use the following version if you installed the package with npm:\n      // tmpl = require(\"blueimp-tmpl\"),\n      // Sample data:\n      data = {\n        title: 'JavaScript Templates',\n        url: 'https://github.com/blueimp/JavaScript-Templates',\n        features: ['lightweight \u0026 fast', 'powerful', 'zero dependencies']\n      }\n    // Override the template loading method:\n    tmpl.load = function (id) {\n      var filename = id + '.html'\n      console.log('Loading ' + filename)\n      return fs.readFileSync(filename, 'utf8')\n    }\n    res.writeHead(200, { 'Content-Type': 'text/x-tmpl' })\n    // Render the content:\n    res.end(tmpl('template', data))\n  })\n  .listen(8080, 'localhost')\nconsole.log('Server running at http://localhost:8080/')\n```\n\nRun the application with the following command:\n\n```sh\nnode server.js\n```\n\n## Requirements\n\nThe JavaScript Templates script has zero dependencies.\n\n## API\n\n### tmpl() function\n\nThe **tmpl()** function is added to the global **window** object and can be\ncalled as global function:\n\n```js\nvar result = tmpl('tmpl-demo', data)\n```\n\nThe **tmpl()** function can be called with the id of a template, or with a\ntemplate string:\n\n```js\nvar result = tmpl('\u003ch3\u003e{%=o.title%}\u003c/h3\u003e', data)\n```\n\nIf called without second argument, **tmpl()** returns a reusable template\nfunction:\n\n```js\nvar func = tmpl('\u003ch3\u003e{%=o.title%}\u003c/h3\u003e')\ndocument.getElementById('result').innerHTML = func(data)\n```\n\n### Templates cache\n\nTemplates loaded by id are cached in the map **tmpl.cache**:\n\n```js\nvar func = tmpl('tmpl-demo'), // Loads and parses the template\n  cached = typeof tmpl.cache['tmpl-demo'] === 'function', // true\n  result = tmpl('tmpl-demo', data) // Uses cached template function\n\ntmpl.cache['tmpl-demo'] = null\nresult = tmpl('tmpl-demo', data) // Loads and parses the template again\n```\n\n### Output encoding\n\nThe method **tmpl.encode** is used to escape HTML special characters in the\ntemplate output:\n\n```js\nvar output = tmpl.encode('\u003c\u003e\u0026\"\\'\\x00') // Renders \"\u0026lt;\u0026gt;\u0026amp;\u0026quot;\u0026#39;\"\n```\n\n**tmpl.encode** makes use of the regular expression **tmpl.encReg** and the\nencoding map **tmpl.encMap** to match and replace special characters, which can\nbe modified to change the behavior of the output encoding.  \nStrings matched by the regular expression, but not found in the encoding map are\nremoved from the output. This allows for example to automatically trim input\nvalues (removing whitespace from the start and end of the string):\n\n```js\ntmpl.encReg = /(^\\s+)|(\\s+$)|[\u003c\u003e\u0026\"'\\x00]/g\nvar output = tmpl.encode('    Banana!    ') // Renders \"Banana\" (without whitespace)\n```\n\n### Local helper variables\n\nThe local variables available inside the templates are the following:\n\n- **o**: The data object given as parameter to the template function (see the\n  next section on how to modify the parameter name).\n- **tmpl**: A reference to the **tmpl** function object.\n- **\\_s**: The string for the rendered result content.\n- **\\_e**: A reference to the **tmpl.encode** method.\n- **print**: Helper function to add content to the rendered result string.\n- **include**: Helper function to include the return value of a different\n  template in the result.\n\nTo introduce additional local helper variables, the string **tmpl.helper** can\nbe extended. The following adds a convenience function for _console.log_ and a\nstreaming function, that streams the template rendering result back to the\ncallback argument (note the comma at the beginning of each variable\ndeclaration):\n\n```js\ntmpl.helper +=\n  ',log=function(){console.log.apply(console, arguments)}' +\n  \",st='',stream=function(cb){var l=st.length;st=_s;cb( _s.slice(l));}\"\n```\n\nThose new helper functions could be used to stream the template contents to the\nconsole output:\n\n```html\n\u003cscript type=\"text/x-tmpl\" id=\"tmpl-demo\"\u003e\n  \u003ch3\u003e{%=o.title%}\u003c/h3\u003e\n  {% stream(log); %}\n  \u003cp\u003eReleased under the\n  \u003ca href=\"{%=o.license.url%}\"\u003e{%=o.license.name%}\u003c/a\u003e.\u003c/p\u003e\n  {% stream(log); %}\n  \u003ch4\u003eFeatures\u003c/h4\u003e\n  \u003cul\u003e\n  {% stream(log); %}\n  {% for (var i=0; i\u003co.features.length; i++) { %}\n      \u003cli\u003e{%=o.features[i]%}\u003c/li\u003e\n      {% stream(log); %}\n  {% } %}\n  \u003c/ul\u003e\n  {% stream(log); %}\n\u003c/script\u003e\n```\n\n### Template function argument\n\nThe generated template functions accept one argument, which is the data object\ngiven to the **tmpl(id, data)** function. This argument is available inside the\ntemplate definitions as parameter **o** (the lowercase letter).\n\nThe argument name can be modified by overriding **tmpl.arg**:\n\n```js\ntmpl.arg = 'p'\n\n// Renders \"\u003ch3\u003eJavaScript Templates\u003c/h3\u003e\":\nvar result = tmpl('\u003ch3\u003e{%=p.title%}\u003c/h3\u003e', { title: 'JavaScript Templates' })\n```\n\n### Template parsing\n\nThe template contents are matched and replaced using the regular expression\n**tmpl.regexp** and the replacement function **tmpl.func**. The replacement\nfunction operates based on the\n[parenthesized submatch strings](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter).\n\nTo use different tags for the template syntax, override **tmpl.regexp** with a\nmodified regular expression, by exchanging all occurrences of \"{%\" and \"%}\",\ne.g. with \"[%\" and \"%]\":\n\n```js\ntmpl.regexp = /([\\s'\\\\])(?!(?:[^[]|\\[(?!%))*%\\])|(?:\\[%(=|#)([\\s\\S]+?)%\\])|(\\[%)|(%\\])/g\n```\n\nBy default, the plugin preserves whitespace (newlines, carriage returns, tabs\nand spaces). To strip unnecessary whitespace, you can override the **tmpl.func**\nfunction, e.g. with the following code:\n\n```js\nvar originalFunc = tmpl.func\ntmpl.func = function (s, p1, p2, p3, p4, p5, offset, str) {\n  if (p1 \u0026\u0026 /\\s/.test(p1)) {\n    if (\n      !offset ||\n      /\\s/.test(str.charAt(offset - 1)) ||\n      /^\\s+$/g.test(str.slice(offset))\n    ) {\n      return ''\n    }\n    return ' '\n  }\n  return originalFunc.apply(tmpl, arguments)\n}\n```\n\n## Templates syntax\n\n### Interpolation\n\nPrint variable with HTML special characters escaped:\n\n```html\n\u003ch3\u003e{%=o.title%}\u003c/h3\u003e\n```\n\nPrint variable without escaping:\n\n```html\n\u003ch3\u003e{%#o.user_id%}\u003c/h3\u003e\n```\n\nPrint output of function calls:\n\n```html\n\u003ca href=\"{%=encodeURI(o.url)%}\"\u003eWebsite\u003c/a\u003e\n```\n\nUse dot notation to print nested properties:\n\n```html\n\u003cstrong\u003e{%=o.author.name%}\u003c/strong\u003e\n```\n\n### Evaluation\n\nUse **print(str)** to add escaped content to the output:\n\n```html\n\u003cspan\u003eYear: {% var d=new Date(); print(d.getFullYear()); %}\u003c/span\u003e\n```\n\nUse **print(str, true)** to add unescaped content to the output:\n\n```html\n\u003cspan\u003e{% print(\"Fast \u0026amp; powerful\", true); %}\u003c/span\u003e\n```\n\nUse **include(str, obj)** to include content from a different template:\n\n```html\n\u003cdiv\u003e\n  {% include('tmpl-link', {name: \"Website\", url: \"https://example.org\"}); %}\n\u003c/div\u003e\n```\n\n**If else condition**:\n\n```html\n{% if (o.author.url) { %}\n\u003ca href=\"{%=encodeURI(o.author.url)%}\"\u003e{%=o.author.name%}\u003c/a\u003e\n{% } else { %}\n\u003cem\u003eNo author url.\u003c/em\u003e\n{% } %}\n```\n\n**For loop**:\n\n```html\n\u003cul\u003e\n{% for (var i=0; i\u003co.features.length; i++) { %}\n    \u003cli\u003e{%=o.features[i]%}\u003c/li\u003e\n{% } %}\n\u003c/ul\u003e\n```\n\n## Compiled templates\n\nThe JavaScript Templates project comes with a compilation script, that allows\nyou to compile your templates into JavaScript code and combine them with a\nminimal Templates runtime into one combined JavaScript file.\n\nThe compilation script is built for [Node.js](https://nodejs.org/).  \nTo use it, first install the JavaScript Templates project via\n[NPM](https://www.npmjs.org/):\n\n```sh\nnpm install blueimp-tmpl\n```\n\nThis will put the executable **tmpl.js** into the folder **node_modules/.bin**.\nIt will also make it available on your PATH if you install the package globally\n(by adding the **-g** flag to the install command).\n\nThe **tmpl.js** executable accepts the paths to one or multiple template files\nas command line arguments and prints the generated JavaScript code to the\nconsole output. The following command line shows you how to store the generated\ncode in a new JavaScript file that can be included in your project:\n\n```sh\ntmpl.js index.html \u003e tmpl.js\n```\n\nThe files given as command line arguments to **tmpl.js** can either be pure\ntemplate files or HTML documents with embedded template script sections. For the\npure template files, the file names (without extension) serve as template ids.  \nThe generated file can be included in your project as a replacement for the\noriginal **tmpl.js** runtime. It provides you with the same API and provides a\n**tmpl(id, data)** function that accepts the id of one of your templates as\nfirst and a data object as optional second parameter.\n\n## Tests\n\nThe JavaScript Templates project comes with\n[Unit Tests](https://en.wikipedia.org/wiki/Unit_testing).  \nThere are two different ways to run the tests:\n\n- Open test/index.html in your browser or\n- run `npm test` in the Terminal in the root path of the repository package.\n\nThe first one tests the browser integration, the second one the\n[Node.js](https://nodejs.org/) integration.\n\n## License\n\nThe JavaScript Templates script is released under the\n[MIT license](https://opensource.org/licenses/MIT).\n","funding_links":["https://github.com/sponsors/blueimp"],"categories":["Templating Engines","JavaScript","Templating Engines [🔝](#readme)","模板引擎"],"sub_categories":["Runner","运行器","运行器e2e测试"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fblueimp%2FJavaScript-Templates","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fblueimp%2FJavaScript-Templates","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fblueimp%2FJavaScript-Templates/lists"}