How to use Smarty templates in Node.js

Larger projects can lead you to use multiple technologies. Say you are using Smarty templates in PHP and want to use/share same templates in Node.js. jSmart is a way to go. jSmart is a port of the Smarty Template Engine to  make it Javascript Templating Engine. jSmart can work in browsers and CommonJS environments like Node.js. I will demonstrate how we can use jSmart in Node.js

1. Install jSmart from NPM Registry.

$ npm install jsmart --save

2. First create the template with some data we are supposed to render. Say
demo.tpl and its contents are:-

Hello {$name}

3. Create demo.js in the same folder which includes jsmart and fs module.

var fs = require(fs);
require('jsmart');

4. Now we will read the content of template file and create jSmart object which compiles our template.

var fs = require(fs);
require('jsmart');
var tpl = fs.readFileSync('./demo.tpl', {encoding: 'utf-8'});
var compiledTpl = jSmart(tpl);

Note:- I’m reading file synchronously for demo purpose. Best is to read file asynchronously. That’s is what the + point of Node.js.

5. We are ready to assign data to the template and print output of the template.

var fs = require(fs);
require('jsmart');
var tpl = fs.readFileSync('./demo.tpl', {encoding: 'utf-8'});
var compiledTpl = jSmart(tpl);
var output = compiledTpl.fetch({name: 'World'});
console.log(output);

6. Now save the file i.e demo.js. After that, you are ready to execute the file and see the output.

$ node demo.js

7. You would see the string “Hello World“.

On the similar lines, you can use all the features of Smarty. You can find documentation at https://github.com/umakantp/jsmart/wiki.

If you clone the jSmart repo from Github, you would find various examples which demonstrate how jSmart works on a browser, node js and using require.js.

Above demo covers a very basic example of how to use in Node Js. You can always request for advanced integration in the comments. I will be happy to put on more integration example.


UPDATE(06/11/2017) :-

jSmart now has plugins which enable you to use jSmart with other frameworks or tools. I have populated a list over here for you of all the available plugins.

Express JS:- https://www.npmjs.com/package/jsmart-express
Webpack:- https://www.npmjs.com/package/jsmart-loader
Grunt:- https://www.npmjs.com/package/grunt-jsmart

 

 

6 Comments

    1. I have actually never worked with expressjs. If I find time to explore, I’ll definitely add another blog for expressjs.

      1. Hey Ningappa,

        There is an update. You can use this for your express framework with the following package. More details are provided in the package documentation:-https://www.npmjs.com/package/jsmart-express

  1. Well, in express all you have to do is to create your smarty variable and pass the template name to be rendered as you route to your files in express

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.