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 way to go. jSmart is a port of the Smarty Template Engine to Javascript. 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.

2. First create template with some data we are supposed to render. Sa
y demo.tpl and it contents are:-

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

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

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 assign data to the template and print output of the template.

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

7. You would see 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 shows how jSmart works on browser and using require.js.

I have demoed a quick tutorial. If you are expecting something more from tutorial / demo, do let me know in the comments. I will happy to update.

 

 

JavaScript library compatible with RequireJs, jQuery and Node.js

Last night, I was updating is_email JavaScript library so that it supports jQuery, RequireJS and Node.js. I found information for each library but on different blogs. I didn’t find complete set information at one place. As each of my blog says, I would be putting it here  in the hope that it would be accessible all at one place.

I would explain with demo example. First wrap whole library in a function, so that even though my library has thousand functions, only the one I needed would go in global scope. In below example I’m creating a library function which checks if variable is undefined.

Now I have wrote my function, now I would want it to be enabled or compatible with RequireJS. Check if define is a function and it is a AMD loader then define our function. That’s it. Checkout below example.

You want that your library can also be used as Node module. There are few more steps to create Node module. Checkout tutorial for how Node.js module is created. In below I would just show to expose your lib/function to Node as module.

Check if “module” is defined and “exports” is defined, if yes then we assume it is Node whose using/calling a JS file or JS funcion.

Last, how to enable support for jQuery. There are many ways to do expose/add your function to jQuery. I would demo two methods.

If you are looking for complete tutorial for jQuery plugin, then you are on wrong blog as I’m just demoing how to enable jQuery support. Please go to for writing your own jquery plugin.

We can combine all these above 3 examples into one and enable support /compatibility for RequireJS, jQuery and Node. One of the working example is is_email library which validates your email against relevant RFCs.

If I’m missing some information or you have any suggestions, doubts or questions do write your comments/thoughts on the blog..

Want to have APC with PHP 5.5?

Today I was upgrading PHP on my production server. I went up to www.php.net and found that latest version released was PHP 5.5.1. As usual as our dev practice first thing was to look around if it had any already open bugs which affects my application. Found that JSON extension developed by Douglas Crockford was replaced with https://github.com/remicollet/pecl-json-c because of some license woes. As long as JSON works, it was not a problem (You can read more about it on http://philsturgeon.co.uk/blog/2013/08/fud-cracker-php-55-never-lost-json-support).

Another problem I came across was that APC was not supported in the latest version. I tired and tried compiling each version of APC with PHP 5.5.1 but no luck. Again I saw talks on some forums that APC will be always disabled for further PHP version and Zend optimizer+ can be used replacement to APC. Wait… I guess prople are confused here. If you are using APC for opcaching then Zend optimizer+, but if you are using APC for user caching then you can use Memcached or may be Redis is better choice.

But I was not convinced with any of these solutions. Then googling I came across Github repo of APC which works. But I’m still worried because it is still in development version, not stable and so not good to use on production.

Here comes APCu version 4.0.1, which is replacement of APC for user cache. APCu is fork of APC. It works perfectly fine. Right now its on my production. Hurray. Thanks to  Joe Watkins.

APCu doesn’t have opcache within it but user cache only. Leaving no option behind I had to go ahead with Zend optimizer+. Before going on production, I had done some benchmarking with and without Zend optimizer+ using http-perf and there was huge difference (good results). Moved it to production and as of now its serving well. I would update this page if I face any issues ahead.

Do let me know in comments  if you have any inputs / suggestions / different experiences.

is_email for JavaScript, Node, RequireJS and jQuery

Today email address are asked by many websites for signing up for there services. How do they validate email address? May be using code which ignores RFCs. Say if your ISP has issued you email address which flouts RFC conventions and it is invalid. If you can send and receive emails on that why does it matter its invalid?

Here comes is_email originally developed by Dominic Sayers written in Java, C# and PHP which validates email address.

My project requirement was to validate email in JavaScript. Tried various libraries available on the web and i failed getting one like is_email. I myself ported the code written by Dominic Sayers in PHP to JavaScript.

I have shared it on Github in the hope someday, someone like me would need it too. Now is_mail library can be used in Node as module. Find it on npm registry as ‘is_email’ package.

You can also use it with jQuery and RequireJS. Find details on how it can used in is_email Github repository README.md file.

If you find bugs please open issue on Github or feel free to fork and send pull request.

How to cache compiled templates of Haml-js in Node.js

I recently came across Node.js technology, which is nothing but JavaScript based event driven server side platform. Further studies made me use Haml-js for templating. As of I studied, using both of them we can make good maintainable and scalable applications.

For improving Haml-js performance, I had to cache the compiled templates on some location or using some mechanism. I used Memcached in Node.js to store compiled templates.

Considering that you already know node.js and haml-js, If not that please first thing is getting installed Node.js and Haml.js on your machines. Steps for Node.js can be follow here and Haml-js can be followed here. Once both of the steps are followed correctly. Have some basic understanding of both with some examples.  Then proceed with below example to see how I implemented memcached templates of haml-js in node.js

We will create new directory for our example as follows:-

Here we can create sample template file as sample.haml with some markup into it.

We will create a JavaScript file mem.js which will store and load compiled template from memcachde and throw the output on HTTP Server. In this first we will load all the modules and connect to memcached server and have some dynamic data.

I have my local memcached setup on 127.0.0.1 on 11211 port. You can replace the values with the ones of yours. Now time comes to create a HTTP server.

Here its very clear that I have just created a HTTP server which prints out text “Open blank test” when you point your browser to http://127.0.0.1:1337/

We will modify these code and render actual template

Now you see actual HTML coming from template and data from data variable. var haml has value from file sample.haml and then in next line we compile the file data and  store in var js. Line below that has Haml.execute function which renders the compiled template. In between of this we will have memcached to store the compile file.

First we try value for var js from memcached whose value is stored in “compiled”. If we find it we use the same, if we don’t find it then we read the sample.haml and compile store in memcached. We close memcached connection as we will further no more use the memcached in the cxample.

You can download the complete example by clicking here.

I will surely update the this blog with more explanations on each of the functions and steps.

In Android, How to obtain Uri of image on SD-Card

How to get URI of image stored on SD-Card?

Step 1:- Read the image from SD-Card.

Step 2:- Once you get object of image file, you can get URI of the image.

Next:-
You ready to use URI wherever you want. Below e.g. shows we can use it to start intent for the same image.

Not very tough, but love sharing this stuff.

 

Android Emulator, localhost and host files on Windows

We all use emulator with comes with Android SDK to test, how app / websites behave in Android devices.

While working on my applications I wanted to access my localhost which was apache server. I tired using IP address as 127.0.0.1 and typing http://localhost many times. But then I gone through the Android Developer site and found that IP Address to access localhost is http://10.0.2.2
This is because 127.0.0.1 is IP address for locahost of Emulator itself.

Going forward came across one more similar problem. I had setup one xml API on my localhost and added host entry in hosts file of windows which is located at “C:\WINDOWS\system32\drivers\etc“. But the host entry was not working for emulator browser and not even in the app. Here goes the solution for the problem:-

Step 1:-
First open start your emulator from command line. Go to /android-sdk-windows\tools and then type below command.

Note:- Remember that you need to pass partition size and If you don’t pass it then will get error “failed to copy ‘c:\temp\hosts’ to ‘/system/etc/hosts’: Out of memory” in the 5th step.

Step 2:-
Now once emulator is loaded completely with home screen. Open another command line, Go to /android-sdk-windows\platform-tools and type below command to remount the device image as writable:

Step 3:-
Now get the copy of existing file from host computer i.e. emulator to some temporary location.

Step 4:-
Go to your C drive and edit the hosts file and put your host entries:-
127.0.0.1 localhost
10.0.2.2 www.myfirstdomain.com
10.0.2.3 myotherhost

Step 5:-
Once you save the file. Now we should replace the original file of emulator with the new one.

Here you go. Now you can browse the site in browser or you can use API which will your host file entry.

Remember that this is not permanent. You need to do this each time you want to use host file entries. You can repeat step1, step2 and step5. You already have file with you so need to pull and make changes again so step 3 and step 4 is avoided.

Please make sure that you put your comments that If you understand this tutorial easily or it was complicated for you. :)

 

Android ListView with separate headers and images loading from remote server

ListView is one of the commonly used widget in Android. You might have used normal ListView which is just the list of things (text/images). Sometimes you might want to use ListView which has sections or headers. There were no straight forward(easy ways) to do this in Android.

Jeff Sharkeys shown us way for creating such ListView. It was limited to load images from local. Many of us including me was looking out for something which loads images from remote server.
Android ListView with separate headers
Putting it all together I have used SeperatedListAdapter and CursorAdapter for showing the ListView. See the example at the right side(image not very clear).

First lets create XML which we will use for ListView.

1. demoheader.xml – XML file which holds layout for header in list.
2. demorow.xml – XML file which holds layout for row in the list view under each header.

Now we have 2 adapters which are from Jeff Sharkeys’ example used for Separating list.

1. SeperatedListAdapter – Accepts the other adapters and divides them into sections.
2. ObservableAdapter – Helps SeperatedListAdapter for updating section list changes.

Now we are ready to draw list. In onCreate function create object of SeperatedListAdapter passing it on context and header layout. After that we should have sections. For example we can have two sections variables as follows:

Each of the above List item value will have list of map variable which has string and url to be loaded from remote location. It can be found in MainActivity file that shows how I had added sections.

In the same file you will find that I have ExAdapter which extends CursorAdapter and loads images from remote server. For loading images I have used ImageThreadLoader class which loads image from remote server which has 2 levels of caching(Disk and Soft reference), which helps improve performance of ListView.

That’s it. You can checkout complete demo project at Google Code. Any suggestions / issues, let me know in the comments.