Underscore.js mustache polarizing template

Tweet about this on TwitterShare on FacebookShare on LinkedInShare on Google+

Underscore.js template function uses “<%= %>” as a polarising symbol which sometimes causes error on Java, Ruby, and so on. This is because Those languages usually employs exactly the same polarising.
This case requires you to chose one of these options.

1. Use another template functions like “Mustache.js” or “Handlebars”s.
2. Set polarising values with “_.templateSettings” method.

The alternative two template frameworks are not good at handling logical process, such as the non-boolean conditional or the for-loop statement. Therefore, the better solution is #2, using “templateSettings”.

_.templateSettings

The code is quite simple as follows. This time employs “{{ }}” for JavaScript statements and “{{= }}” for variables.

JavaScript

Template script

Underscore.js template function

Tweet about this on TwitterShare on FacebookShare on LinkedInShare on Google+

Underscore.js provides a template function where JavaScript template codes are compiled and rendered to html.
It is known as one used in Backbone.js applications.

Basic rendering

Here shows a very very basic usage. A template script “#main-template” will be rendered in #main container.

Interpolated variable

Passing object data to _.template() enables rendering reflecting the object data.
Variables in the object are interpolated by “<%= %>“.

Conditional clause

Like variables, conditional statements are interpolated by “<% %>” with no equal.

Loop

The syntax is same as the conditional.
Underscore.js functon “_.each()” can be used, while any JavaScript looping function like “for () {}” can be used.

jQuery Colorbox multiple inline contents

Tweet about this on TwitterShare on FacebookShare on LinkedInShare on Google+

Besides image gallery, there seems to be no way to switch multiple inline contents with jQuery Colorbox plugin.
Here, let me introduce an approach using Underscore.js template function.

[Colorbox]    Colorbox – a jQuery lightbox
[Underscore.js]    Underscore.js

Colorbox multiple inline contens with Underscore.js

Demo -Colorbox multi inline content with Underscore.js

HTML

Set the following elements.

  1. Button triggering the modal container. (“button.trig”)
  2. Modal container element (“div#modal-container > div#modal”)
  3. Template element (“script#modal-template1″ & “script#modal-template2″)
  4. Set JS files (jQuery, colorbox, underscore, and main js)

JS (run.js)

  1. Set event on trigger button opening the modal content.(openFirst)
  2. The modal is from “script#modal-template1″ handled by underscore.
  3. The first content has a button “NEXT” triggering the 2nd content. (openSecond)
  4. The second content has a button “BACK” triggering the 1st content. (openFirst)

CSS (SCSS)