RequireJS: More with modules - Templates

Find the previous episode here.

Checkout the part 3 branch
git checkout -b part3.0 origin/part3.0

We have created the routing and added a test module to the application. Lets try to add more to module.

        Am going to use RequireJS "Text" plugin for templating along with  Underscore.js and Jquery
    An AMD loader plugin for requireJS to load text resouces. We will load html using text.
    "Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects."
underscore provides a powerfull templating option. You could try lodash also which is a fork of UnderscoreJS

Let's do some coding now. First we need to create a template in html.
We will extract this code from index.html and will create a new html in modules/home/templates/home.html

<li><a href="#home">Home</a></li>
<li><a href="#employee">Employees</a></li>
<li><a href="#project">Projects</a></li>

and add an div with id "maincontent" in index.html where we will add the templates using jquery.
Now we need to require necessary modules for home controller. We need to require jquery, underscore and text plugins.
define(['jquery', 'underscore', 'text!./templates/Home.html'], function($, _, tmpl) {

For requireJS we need to load the module which will be injected using array and can be accessed as a parameter in the function. "Text" will load the html file as a plain text file. Using jquery we will convert into an jquery element and using underscore we will pass data to the template.

var utmpl = _.template(tmpl);

So we have looked in to how to use modules as well as templating the project. 


Popular posts from this blog

Configure PostgreSQL and phpPgAdmin in WAMP

Angular - 4 year road map

Flash FLV player using PHP