Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork656
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.
License
blueimp/JavaScript-Templates
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
1KB lightweight, fast & powerful JavaScript templating engine with zerodependencies.
Compatible with server-side environments likeNode.js,module loaders likeRequireJS orwebpack and all web browsers.
Install theblueimp-tmpl package withNPM:
npm install blueimp-tmpl
Include the (minified) JavaScript Templates script in your HTML markup:
<scriptsrc="js/tmpl.min.js"></script>
Add a script section with type"text/x-tmpl", a uniqueid property andyour template definition as content:
<scripttype="text/x-tmpl"id="tmpl-demo"><h3>{%=o.title%}</h3><p>Releasedunderthe<ahref="{%=o.license.url%}">{%=o.license.name%}</a>.</p><h4>Features</h4><ul>{%for(vari=0;i<o.features.length;i++){%}<li>{%=o.features[i]%}</li>{%}%} </ul></script>
"o" (the lowercase letter) is a reference to the data parameter of thetemplate function (see the API section on how to modify this identifier).
In your application code, create a JavaScript object to use as data for thetemplate:
vardata={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 aJSON resource.
Render the result by calling thetmpl() method with the id of the templateand the data object as arguments:
document.getElementById('result').innerHTML=tmpl('tmpl-demo',data)
The following is an example how to use the JavaScript Templates engine on theserver-side withNode.js.
Install theblueimp-tmpl package withNPM:
npm install blueimp-tmpl
Add a filetemplate.html with the following content:
<!DOCTYPE HTML><title>{%=o.title%}</title><h3><ahref="{%=o.url%}">{%=o.title%}</a></h3><h4>Features</h4><ul>{% for (var i=0; i<o.features.length;i++){%}<li>{%=o.features[i]%}</li>{% } %}</ul>
Add a fileserver.js with the following content:
require('http').createServer(function(req,res){varfs=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){varfilename=id+'.html'console.log('Loading '+filename)returnfs.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/')
Run the application with the following command:
node server.js
The JavaScript Templates script has zero dependencies.
Thetmpl() function is added to the globalwindow object and can becalled as global function:
varresult=tmpl('tmpl-demo',data)
Thetmpl() function can be called with the id of a template, or with atemplate string:
varresult=tmpl('<h3>{%=o.title%}</h3>',data)
If called without second argument,tmpl() returns a reusable templatefunction:
varfunc=tmpl('<h3>{%=o.title%}</h3>')document.getElementById('result').innerHTML=func(data)
Templates loaded by id are cached in the maptmpl.cache:
varfunc=tmpl('tmpl-demo'),// Loads and parses the templatecached=typeoftmpl.cache['tmpl-demo']==='function',// trueresult=tmpl('tmpl-demo',data)// Uses cached template functiontmpl.cache['tmpl-demo']=nullresult=tmpl('tmpl-demo',data)// Loads and parses the template again
The methodtmpl.encode is used to escape HTML special characters in thetemplate output:
varoutput=tmpl.encode('<>&"\'\x00')// Renders "<>&"'"
tmpl.encode makes use of the regular expressiontmpl.encReg and theencoding maptmpl.encMap to match and replace special characters, which canbe modified to change the behavior of the output encoding.
Strings matched by the regular expression, but not found in the encoding map areremoved from the output. This allows for example to automatically trim inputvalues (removing whitespace from the start and end of the string):
tmpl.encReg=/(^\s+)|(\s+$)|[<>&"'\x00]/gvaroutput=tmpl.encode(' Banana! ')// Renders "Banana" (without whitespace)
The local variables available inside the templates are the following:
- o: The data object given as parameter to the template function (see thenext section on how to modify the parameter name).
- tmpl: A reference to thetmpl function object.
- _s: The string for the rendered result content.
- _e: A reference to thetmpl.encode method.
- print: Helper function to add content to the rendered result string.
- include: Helper function to include the return value of a differenttemplate in the result.
To introduce additional local helper variables, the stringtmpl.helper canbe extended. The following adds a convenience function forconsole.log and astreaming function, that streams the template rendering result back to thecallback argument (note the comma at the beginning of each variabledeclaration):
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 theconsole output:
<scripttype="text/x-tmpl"id="tmpl-demo"><h3>{%=o.title%}</h3>{%stream(log);%}<p>Released under the<ahref="{%=o.license.url%}">{%=o.license.name%}</a>.</p>{%stream(log);%}<h4>Features</h4><ul>{%stream(log);%}{%for(vari=0;i<o.features.length;i++){%}<li>{%=o.features[i]%}</li>{%stream(log);%}{%}%} </ul>{%stream(log);%}</script>
The generated template functions accept one argument, which is the data objectgiven to thetmpl(id, data) function. This argument is available inside thetemplate definitions as parametero (the lowercase letter).
The argument name can be modified by overridingtmpl.arg:
tmpl.arg='p'// Renders "<h3>JavaScript Templates</h3>":varresult=tmpl('<h3>{%=p.title%}</h3>',{title:'JavaScript Templates'})
The template contents are matched and replaced using the regular expressiontmpl.regexp and the replacement functiontmpl.func. The replacementfunction operates based on theparenthesized submatch strings.
To use different tags for the template syntax, overridetmpl.regexp with amodified regular expression, by exchanging all occurrences of "{%" and "%}",e.g. with "[%" and "%]":
tmpl.regexp=/([\s'\\])(?!(?:[^[]|\[(?!%))*%\])|(?:\[%(=|#)([\s\S]+?)%\])|(\[%)|(%\])/g
By default, the plugin preserves whitespace (newlines, carriage returns, tabsand spaces). To strip unnecessary whitespace, you can override thetmpl.funcfunction, e.g. with the following code:
varoriginalFunc=tmpl.functmpl.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' '}returnoriginalFunc.apply(tmpl,arguments)}
Print variable with HTML special characters escaped:
<h3>{%=o.title%}</h3>
Print variable without escaping:
<h3>{%#o.user_id%}</h3>
Print output of function calls:
<ahref="{%=encodeURI(o.url)%}">Website</a>
Use dot notation to print nested properties:
<strong>{%=o.author.name%}</strong>
Useprint(str) to add escaped content to the output:
<span>Year: {% var d=new Date(); print(d.getFullYear()); %}</span>
Useprint(str, true) to add unescaped content to the output:
<span>{% print("Fast & powerful", true); %}</span>
Useinclude(str, obj) to include content from a different template:
<div> {% include('tmpl-link', {name: "Website", url: "https://example.org"}); %}</div>
If else condition:
{% if (o.author.url) { %}<ahref="{%=encodeURI(o.author.url)%}">{%=o.author.name%}</a>{% } else { %}<em>No author url.</em>{% } %}
For loop:
<ul>{% for (var i=0; i<o.features.length;i++){%}<li>{%=o.features[i]%}</li>{% } %}</ul>
The JavaScript Templates project comes with a compilation script, that allowsyou to compile your templates into JavaScript code and combine them with aminimal Templates runtime into one combined JavaScript file.
The compilation script is built forNode.js.
To use it, first install the JavaScript Templates project viaNPM:
npm install blueimp-tmpl
This will put the executabletmpl.js into the foldernode_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).
Thetmpl.js executable accepts the paths to one or multiple template filesas command line arguments and prints the generated JavaScript code to theconsole output. The following command line shows you how to store the generatedcode in a new JavaScript file that can be included in your project:
tmpl.js index.html> tmpl.js
The files given as command line arguments totmpl.js can either be puretemplate files or HTML documents with embedded template script sections. For thepure template files, the file names (without extension) serve as template ids.
The generated file can be included in your project as a replacement for theoriginaltmpl.js runtime. It provides you with the same API and provides atmpl(id, data) function that accepts the id of one of your templates asfirst and a data object as optional second parameter.
The JavaScript Templates project comes withUnit Tests.
There are two different ways to run the tests:
- Open test/index.html in your browser or
- run
npm test
in the Terminal in the root path of the repository package.
The first one tests the browser integration, the second one theNode.js integration.
The JavaScript Templates script is released under theMIT license.
About
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.
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Packages0
Uh oh!
There was an error while loading.Please reload this page.