Gathering detailed insights and metrics for blueimp-tmpl
Gathering detailed insights and metrics for blueimp-tmpl
Gathering detailed insights and metrics for blueimp-tmpl
Gathering detailed insights and metrics for blueimp-tmpl
tmpl
JavaScript micro templates.
@n8n_io/riot-tmpl
n8n fork of the riot template engine
blueimp-md5
JavaScript MD5 implementation. Compatible with server-side environments like Node.js, module loaders like RequireJS, Browserify or webpack and all web browsers.
@types/blueimp-load-image
TypeScript definitions for blueimp-load-image
1KB lightweight, fast & powerful JavaScript templating engine with zero dependencies. Compatible with server-side environments like node.js, module loaders like RequireJS and all web browsers.
npm install blueimp-tmpl
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
1,727 Stars
127 Commits
659 Forks
111 Watching
2 Branches
2 Contributors
Updated on 26 Nov 2024
Minified
Minified + Gzipped
JavaScript (67.9%)
HTML (20.5%)
CSS (10.84%)
Shell (0.77%)
Cumulative downloads
Total Downloads
Last day
3.3%
15,354
Compared to previous day
Last week
5.4%
78,003
Compared to previous week
Last month
2.9%
335,886
Compared to previous month
Last year
-12.6%
4,320,821
Compared to previous year
1KB lightweight, fast & powerful JavaScript templating engine with zero
dependencies.
Compatible with server-side environments like Node.js,
module loaders like RequireJS or
webpack and all web browsers.
Install the blueimp-tmpl package with NPM:
1npm install blueimp-tmpl
Include the (minified) JavaScript Templates script in your HTML markup:
1<script src="js/tmpl.min.js"></script>
Add a script section with type "text/x-tmpl", a unique id property and your template definition as content:
1<script type="text/x-tmpl" id="tmpl-demo"> 2 <h3>{%=o.title%}</h3> 3 <p>Released under the 4 <a href="{%=o.license.url%}">{%=o.license.name%}</a>.</p> 5 <h4>Features</h4> 6 <ul> 7 {% for (var i=0; i<o.features.length; i++) { %} 8 <li>{%=o.features[i]%}</li> 9 {% } %} 10 </ul> 11</script>
"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:
1var data = { 2 title: 'JavaScript Templates', 3 license: { 4 name: 'MIT license', 5 url: 'https://opensource.org/licenses/MIT' 6 }, 7 features: ['lightweight & fast', 'powerful', 'zero dependencies'] 8}
In a real application, this data could be the result of retrieving a JSON resource.
Render the result by calling the tmpl() method with the id of the template and the data object as arguments:
1document.getElementById('result').innerHTML = tmpl('tmpl-demo', data)
The following is an example how to use the JavaScript Templates engine on the server-side with Node.js.
Install the blueimp-tmpl package with NPM:
1npm install blueimp-tmpl
Add a file template.html with the following content:
1<!DOCTYPE HTML> 2<title>{%=o.title%}</title> 3<h3><a href="{%=o.url%}">{%=o.title%}</a></h3> 4<h4>Features</h4> 5<ul> 6{% for (var i=0; i<o.features.length; i++) { %} 7 <li>{%=o.features[i]%}</li> 8{% } %} 9</ul>
Add a file server.js with the following content:
1require('http') 2 .createServer(function (req, res) { 3 var fs = require('fs'), 4 // The tmpl module exports the tmpl() function: 5 tmpl = require('./tmpl'), 6 // Use the following version if you installed the package with npm: 7 // tmpl = require("blueimp-tmpl"), 8 // Sample data: 9 data = { 10 title: 'JavaScript Templates', 11 url: 'https://github.com/blueimp/JavaScript-Templates', 12 features: ['lightweight & fast', 'powerful', 'zero dependencies'] 13 } 14 // Override the template loading method: 15 tmpl.load = function (id) { 16 var filename = id + '.html' 17 console.log('Loading ' + filename) 18 return fs.readFileSync(filename, 'utf8') 19 } 20 res.writeHead(200, { 'Content-Type': 'text/x-tmpl' }) 21 // Render the content: 22 res.end(tmpl('template', data)) 23 }) 24 .listen(8080, 'localhost') 25console.log('Server running at http://localhost:8080/')
Run the application with the following command:
1node server.js
The JavaScript Templates script has zero dependencies.
The tmpl() function is added to the global window object and can be called as global function:
1var result = tmpl('tmpl-demo', data)
The tmpl() function can be called with the id of a template, or with a template string:
1var result = tmpl('<h3>{%=o.title%}</h3>', data)
If called without second argument, tmpl() returns a reusable template function:
1var func = tmpl('<h3>{%=o.title%}</h3>') 2document.getElementById('result').innerHTML = func(data)
Templates loaded by id are cached in the map tmpl.cache:
1var func = tmpl('tmpl-demo'), // Loads and parses the template 2 cached = typeof tmpl.cache['tmpl-demo'] === 'function', // true 3 result = tmpl('tmpl-demo', data) // Uses cached template function 4 5tmpl.cache['tmpl-demo'] = null 6result = tmpl('tmpl-demo', data) // Loads and parses the template again
The method tmpl.encode is used to escape HTML special characters in the template output:
1var 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):
1tmpl.encReg = /(^\s+)|(\s+$)|[<>&"'\x00]/g 2var output = tmpl.encode(' Banana! ') // Renders "Banana" (without whitespace)
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):
1tmpl.helper += 2 ',log=function(){console.log.apply(console, arguments)}' + 3 ",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:
1<script type="text/x-tmpl" id="tmpl-demo"> 2 <h3>{%=o.title%}</h3> 3 {% stream(log); %} 4 <p>Released under the 5 <a href="{%=o.license.url%}">{%=o.license.name%}</a>.</p> 6 {% stream(log); %} 7 <h4>Features</h4> 8 <ul> 9 {% stream(log); %} 10 {% for (var i=0; i<o.features.length; i++) { %} 11 <li>{%=o.features[i]%}</li> 12 {% stream(log); %} 13 {% } %} 14 </ul> 15 {% stream(log); %} 16</script>
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:
1tmpl.arg = 'p' 2 3// Renders "<h3>JavaScript Templates</h3>": 4var result = tmpl('<h3>{%=p.title%}</h3>', { title: 'JavaScript Templates' })
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.
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 "%]":
1tmpl.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:
1var originalFunc = tmpl.func 2tmpl.func = function (s, p1, p2, p3, p4, p5, offset, str) { 3 if (p1 && /\s/.test(p1)) { 4 if ( 5 !offset || 6 /\s/.test(str.charAt(offset - 1)) || 7 /^\s+$/g.test(str.slice(offset)) 8 ) { 9 return '' 10 } 11 return ' ' 12 } 13 return originalFunc.apply(tmpl, arguments) 14}
Print variable with HTML special characters escaped:
1<h3>{%=o.title%}</h3>
Print variable without escaping:
1<h3>{%#o.user_id%}</h3>
Print output of function calls:
1<a href="{%=encodeURI(o.url)%}">Website</a>
Use dot notation to print nested properties:
1<strong>{%=o.author.name%}</strong>
Use print(str) to add escaped content to the output:
1<span>Year: {% var d=new Date(); print(d.getFullYear()); %}</span>
Use print(str, true) to add unescaped content to the output:
1<span>{% print("Fast & powerful", true); %}</span>
Use include(str, obj) to include content from a different template:
1<div> 2 {% include('tmpl-link', {name: "Website", url: "https://example.org"}); %} 3</div>
If else condition:
1{% if (o.author.url) { %} 2<a href="{%=encodeURI(o.author.url)%}">{%=o.author.name%}</a> 3{% } else { %} 4<em>No author url.</em> 5{% } %}
For loop:
1<ul> 2{% for (var i=0; i<o.features.length; i++) { %} 3 <li>{%=o.features[i]%}</li> 4{% } %} 5</ul>
The JavaScript Templates project comes with a compilation script, that allows you to compile your templates into JavaScript code and combine them with a minimal Templates runtime into one combined JavaScript file.
The compilation script is built for Node.js.
To use it, first install the JavaScript Templates project via
NPM:
1npm install blueimp-tmpl
This will put the executable tmpl.js into the folder node_modules/.bin. It will also make it available on your PATH if you install the package globally (by adding the -g flag to the install command).
The tmpl.js executable accepts the paths to one or multiple template files as command line arguments and prints the generated JavaScript code to the console output. The following command line shows you how to store the generated code in a new JavaScript file that can be included in your project:
1tmpl.js index.html > tmpl.js
The files given as command line arguments to tmpl.js can either be pure
template files or HTML documents with embedded template script sections. For the
pure template files, the file names (without extension) serve as template ids.
The generated file can be included in your project as a replacement for the
original tmpl.js runtime. It provides you with the same API and provides a
tmpl(id, data) function that accepts the id of one of your templates as
first and a data object as optional second parameter.
The JavaScript Templates project comes with
Unit Tests.
There are two different ways to run the tests:
npm test
in the Terminal in the root path of the repository package.The first one tests the browser integration, the second one the Node.js integration.
The JavaScript Templates script is released under the MIT license.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
7 existing vulnerabilities detected
Details
Reason
Found 0/30 approved changesets -- score normalized to 0
Reason
project is archived
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no SAST tool detected
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More