diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..048b1cf --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +github: [blueimp] diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..d8c4a79 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,18 @@ +name: Test + +on: [push, pull_request] + +jobs: + test: + runs-on: ubuntu-latest + strategy: + matrix: + node-version: [14, 16] + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-node@v2 + with: + node-version: ${{ matrix.node-version }} + - run: npm install + - run: npm run build --if-present + - run: npm run test diff --git a/.gitignore b/.gitignore index 9daa824..3c3629e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1 @@ -.DS_Store node_modules diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..d6a9d74 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,20 @@ +MIT License + +Copyright © 2011 Sebastian Tschan, https://blueimp.net + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Makefile b/Makefile deleted file mode 100644 index 659aa99..0000000 --- a/Makefile +++ /dev/null @@ -1,4 +0,0 @@ -.PHONY: js - -js: - uglifyjs -nc tmpl.js > tmpl.min.js diff --git a/README.md b/README.md index 5f9d6e9..d8281b2 100644 --- a/README.md +++ b/README.md @@ -1,65 +1,101 @@ # JavaScript Templates -## Demo -[JavaScript Templates Demo](http://blueimp.github.com/JavaScript-Templates/) +## Contents + +- [Demo](https://blueimp.github.io/JavaScript-Templates/) +- [Description](#description) +- [Usage](#usage) + - [Client-side](#client-side) + - [Server-side](#server-side) +- [Requirements](#requirements) +- [API](#api) + - [tmpl() function](#tmpl-function) + - [Templates cache](#templates-cache) + - [Output encoding](#output-encoding) + - [Local helper variables](#local-helper-variables) + - [Template function argument](#template-function-argument) + - [Template parsing](#template-parsing) +- [Templates syntax](#templates-syntax) + - [Interpolation](#interpolation) + - [Evaluation](#evaluation) +- [Compiled templates](#compiled-templates) +- [Tests](#tests) +- [License](#license) + +## Description + +1KB lightweight, fast & powerful JavaScript templating engine with zero +dependencies. +Compatible with server-side environments like [Node.js](https://nodejs.org/), +module loaders like [RequireJS](https://requirejs.org/) or +[webpack](https://webpack.js.org/) and all web browsers. ## Usage ### Client-side + +Install the **blueimp-tmpl** package with [NPM](https://www.npmjs.org/): + +```sh +npm install blueimp-tmpl +``` + Include the (minified) JavaScript Templates script in your HTML markup: ```html - + ``` -Add a script section with type **"text/x-tmpl"**, a unique **id** property and your template definition as content: +Add a script section with type **"text/x-tmpl"**, a unique **id** property and +your template definition as content: ```html ``` -**"o"** (the lowercase letter) is a reference to the data parameter of the template function (see the API section on how to modify this identifier). +**"o"** (the lowercase letter) is a reference to the data parameter of the +template function (see the API section on how to modify this identifier). -In your application code, create a JavaScript object to use as data for the template: +In your application code, create a JavaScript object to use as data for the +template: ```js var data = { - "title": "JavaScript Templates", - "license": { - "name": "MIT license", - "url": "http://www.opensource.org/licenses/MIT" - }, - "features": [ - "lightweight & fast", - "powerful", - "zero dependencies" - ] -}; + title: 'JavaScript Templates', + license: { + name: 'MIT license', + url: 'https://opensource.org/licenses/MIT' + }, + features: ['lightweight & fast', 'powerful', 'zero dependencies'] +} ``` -In a real application, this data could be the result of retrieving a [JSON](http://json.org/) resource. +In a real application, this data could be the result of retrieving a +[JSON](https://json.org/) resource. -Render the result by calling the **tmpl()** method with the id of the template and the data object as arguments: +Render the result by calling the **tmpl()** method with the id of the template +and the data object as arguments: ```js -document.getElementById("result").innerHTML = tmpl("tmpl-demo", data); +document.getElementById('result').innerHTML = tmpl('tmpl-demo', data) ``` ### Server-side -The following is an example how to use the JavaScript Templates engine on the server-side with [node.js](http://nodejs.org/). +The following is an example how to use the JavaScript Templates engine on the +server-side with [Node.js](https://nodejs.org/). -Create a new directory and add the **tmpl.js** file. Or alternatively, install the **blueimp-tmpl** package with [npm](http://npmjs.org/): +Install the **blueimp-tmpl** package with [NPM](https://www.npmjs.org/): ```sh npm install blueimp-tmpl @@ -82,33 +118,31 @@ Add a file **template.html** with the following content: Add a file **server.js** with the following content: ```js -require("http").createServer(function (req, res) { - var fs = require("fs"), - // The tmpl module exports the tmpl() function: - tmpl = require("./tmpl").tmpl, - // Use the following version if you installed the package with npm: - // tmpl = require("blueimp-tmpl").tmpl, - // Sample data: - data = { - "title": "JavaScript Templates", - "url": "https://github.com/blueimp/JavaScript-Templates", - "features": [ - "lightweight & fast", - "powerful", - "zero dependencies" - ] - }; +require('http') + .createServer(function (req, res) { + var fs = require('fs'), + // The tmpl module exports the tmpl() function: + tmpl = require('./tmpl'), + // Use the following version if you installed the package with npm: + // tmpl = require("blueimp-tmpl"), + // Sample data: + data = { + title: 'JavaScript Templates', + url: 'https://github.com/blueimp/JavaScript-Templates', + features: ['lightweight & fast', 'powerful', 'zero dependencies'] + } // Override the template loading method: tmpl.load = function (id) { - var filename = id + ".html"; - console.log("Loading " + filename); - return fs.readFileSync(filename, "utf8"); - }; - res.writeHead(200, {"Content-Type": "text/x-tmpl"}); + var filename = id + '.html' + console.log('Loading ' + filename) + return fs.readFileSync(filename, 'utf8') + } + res.writeHead(200, { 'Content-Type': 'text/x-tmpl' }) // Render the content: - res.end(tmpl("template", data)); -}).listen(8080, "localhost"); -console.log("Server running at http://localhost:8080/"); + res.end(tmpl('template', data)) + }) + .listen(8080, 'localhost') +console.log('Server running at http://localhost:8080/') ``` Run the application with the following command: @@ -118,135 +152,171 @@ node server.js ``` ## Requirements + The JavaScript Templates script has zero dependencies. ## API ### tmpl() function -The **tmpl()** function is added to the global **window** object and can be called as global function: + +The **tmpl()** function is added to the global **window** object and can be +called as global function: ```js -var result = tmpl("tmpl-demo", data); +var result = tmpl('tmpl-demo', data) ``` -The **tmpl()** function can be called with the id of a template, or with a template string: +The **tmpl()** function can be called with the id of a template, or with a +template string: ```js -var result = tmpl("

{%=o.title%}

", data); +var result = tmpl('

{%=o.title%}

', data) ``` -If called without second argument, **tmpl()** returns a reusable template function: +If called without second argument, **tmpl()** returns a reusable template +function: ```js -var func = tmpl("

{%=o.title%}

"); -document.getElementById("result").innerHTML = func(data); +var func = tmpl('

{%=o.title%}

') +document.getElementById('result').innerHTML = func(data) ``` ### Templates cache + Templates loaded by id are cached in the map **tmpl.cache**: ```js -var func = tmpl("tmpl-demo"), // Loads and parses the template - cached = typeof tmpl.cache["tmpl-demo"] === "function", // true - result = tmpl("tmpl-demo", data); // Uses cached template function +var func = tmpl('tmpl-demo'), // Loads and parses the template + cached = typeof tmpl.cache['tmpl-demo'] === 'function', // true + result = tmpl('tmpl-demo', data) // Uses cached template function -tmpl.cache["tmpl-demo"] = null; -result = tmpl("tmpl-demo", data); // Loads and parses the template again +tmpl.cache['tmpl-demo'] = null +result = tmpl('tmpl-demo', data) // Loads and parses the template again ``` ### Output encoding -The method **tmpl.encode** is used to escape HTML special characters in the template output: + +The method **tmpl.encode** is used to escape HTML special characters in the +template output: ```js -var output = tmpl.encode("<>&\"'\x00"); // Renders "<>&"'" +var output = tmpl.encode('<>&"\'\x00') // Renders "<>&"'" ``` -**tmpl.encode** makes use of the regular expression **tmpl.encReg** and the encoding map **tmpl.encMap** to match and replace special characters, which can be modified to change the behavior of the output encoding. -Strings matched by the regular expression, but not found in the encoding map are removed from the output. This allows for example to automatically trim input values (removing whitespace from the start and end of the string): +**tmpl.encode** makes use of the regular expression **tmpl.encReg** and the +encoding map **tmpl.encMap** to match and replace special characters, which can +be modified to change the behavior of the output encoding. +Strings matched by the regular expression, but not found in the encoding map are +removed from the output. This allows for example to automatically trim input +values (removing whitespace from the start and end of the string): ```js -tmpl.encReg = /(^\s+)|(\s+$)|[<>&"'\x00]/g; -var output = tmpl.encode(" Banana! "); // Renders "Banana" (without whitespace) +tmpl.encReg = /(^\s+)|(\s+$)|[<>&"'\x00]/g +var output = tmpl.encode(' Banana! ') // Renders "Banana" (without whitespace) ``` ### Local helper variables -The local variables available inside the templates are the following: -* **o**: The data object given as parameter to the template function (see the next section on how to modify the parameter name). -* **tmpl**: A reference to the **tmpl** function object. -* **_s**: The string for the rendered result content. -* **_e**: A reference to the **tmpl.encode** method. -* **print**: Helper function to add content to the rendered result string. -* **include**: Helper function to include the return value of a different template in the result. +The local variables available inside the templates are the following: -To introduce additional local helper variables, the string **tmpl.helper** can be extended. The following adds a convenience function for *console.log* and a streaming function, that streams the template rendering result back to the callback argument (note the comma at the beginning of each variable declaration): +- **o**: The data object given as parameter to the template function (see the + next section on how to modify the parameter name). +- **tmpl**: A reference to the **tmpl** function object. +- **\_s**: The string for the rendered result content. +- **\_e**: A reference to the **tmpl.encode** method. +- **print**: Helper function to add content to the rendered result string. +- **include**: Helper function to include the return value of a different + template in the result. + +To introduce additional local helper variables, the string **tmpl.helper** can +be extended. The following adds a convenience function for _console.log_ and a +streaming function, that streams the template rendering result back to the +callback argument (note the comma at the beginning of each variable +declaration): ```js -tmpl.helper += ",log=function(){console.log.apply(console, arguments)}" + - ",st='',stream=function(cb){var l=st.length;st=_s;cb( _s.slice(l));}"; +tmpl.helper += + ',log=function(){console.log.apply(console, arguments)}' + + ",st='',stream=function(cb){var l=st.length;st=_s;cb( _s.slice(l));}" ``` -Those new helper functions could be used to stream the template contents to the console output: +Those new helper functions could be used to stream the template contents to the +console output: ```html ``` ### Template function argument -The generated template functions accept one argument, which is the data object given to the **tmpl(id, data)** function. This argument is available inside the template definitions as parameter **o** (the lowercase letter). + +The generated template functions accept one argument, which is the data object +given to the **tmpl(id, data)** function. This argument is available inside the +template definitions as parameter **o** (the lowercase letter). The argument name can be modified by overriding **tmpl.arg**: ```js -tmpl.arg = "p"; +tmpl.arg = 'p' // Renders "

JavaScript Templates

": -var result = tmpl("

{%=p.title%}

", {title: "JavaScript Templates"}); +var result = tmpl('

{%=p.title%}

', { title: 'JavaScript Templates' }) ``` ### Template parsing -The template contents are matched and replaced using the regular expression **tmpl.regexp** and the replacement function **tmpl.func**. The replacement function operates based on the [parenthesized submatch strings](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter). -To use different tags for the template syntax, override **tmpl.regexp** with a modified regular expression, by exchanging all occurrences of "**\\{%**" and "**%\\}**", e.g. with "**\\[%**" and "**%\\]**": +The template contents are matched and replaced using the regular expression +**tmpl.regexp** and the replacement function **tmpl.func**. The replacement +function operates based on the +[parenthesized submatch strings](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter). + +To use different tags for the template syntax, override **tmpl.regexp** with a +modified regular expression, by exchanging all occurrences of "{%" and "%}", +e.g. with "[%" and "%]": ```js -tmpl.regexp = /([\s'\\])(?![^%]*%\])|(?:\[%(=|#)([\s\S]+?)%\])|(\[%)|(%\])/g; +tmpl.regexp = /([\s'\\])(?!(?:[^[]|\[(?!%))*%\])|(?:\[%(=|#)([\s\S]+?)%\])|(\[%)|(%\])/g ``` -By default, the plugin preserves whitespace (newlines, carriage returns, tabs and spaces). To strip unnecessary whitespace, you can override the **tmpl.func** function, e.g. with the following code: +By default, the plugin preserves whitespace (newlines, carriage returns, tabs +and spaces). To strip unnecessary whitespace, you can override the **tmpl.func** +function, e.g. with the following code: ```js -var originalFunc = tmpl.func; +var originalFunc = tmpl.func tmpl.func = function (s, p1, p2, p3, p4, p5, offset, str) { - if (p1 && /\s/.test(p1)) { - if (!offset || /\s/.test(str.charAt(offset - 1)) || - /^\s+$/g.test(str.slice(offset))) { - return ''; - } - return ' '; + if (p1 && /\s/.test(p1)) { + if ( + !offset || + /\s/.test(str.charAt(offset - 1)) || + /^\s+$/g.test(str.slice(offset)) + ) { + return '' } - return originalFunc.apply(tmpl, arguments); -}; + return ' ' + } + return originalFunc.apply(tmpl, arguments) +} ``` ## Templates syntax ### Interpolation + Print variable with HTML special characters escaped: ```html @@ -271,15 +341,8 @@ Use dot notation to print nested properties: {%=o.author.name%} ``` -Note that the JavaScript Templates engine prints **falsy** values as empty strings. -That is, **undefined**, **null**, **false**, **0** and **NaN** will all be converted to **''**. -To be able to print e.g. the number 0, convert it to a String before using it as an output variable: - -```html -

{%=0+''%}

-``` - ### Evaluation + Use **print(str)** to add escaped content to the output: ```html @@ -296,21 +359,21 @@ Use **include(str, obj)** to include content from a different template: ```html
-{% include('tmpl-link', {name: "Website", url: "http://example.org/"}); %} + {% include('tmpl-link', {name: "Website", url: "https://example.org/"}); %}
``` -If else condition: +**If else condition**: ```html {% if (o.author.url) { %} - {%=o.author.name%} +{%=o.author.name%} {% } else { %} - No author url. +No author url. {% } %} ``` -For loop: +**For loop**: ```html