Today I learned how to use underscore.js. underscore.js is a javascript library that provides a whole load of useful stuff to help with HTML productivity. I learned how to use underscore.js to create a simple javascript template so that I can program a gallery in HTML easily. First, I included a jquery library from google, and then included the underscore.js file.

<script type="text/javascript" src=""></script>
<script type="text/javascript" src="js/underscore-min.js"></script>

Then, I wrote my template. This will allow me to create my gallery.

<h1> UnderScore </h1>
<div class="gallery"></div>
<script class="template" type="text/html">
    <% _.each(rc.imgItems, function(item){ %>
          <a href="images/<%- item.largeimg %>" >
            <img src="<%- item.thumbnail %>" width=200 height=200 />
    <% }); %>

What allows the template to work is the <%- item.[variable] %> inside the HTML code.
This will be sent to the underscore.js file to be translated into my desired HTML code in the next step.

    var tpl_data = {
                thumbnail: ""
                thumbnail: ""
                thumbnail: ""

    var tpl = $("script.template").html();
    var output = _.template(tpl, {rc: tpl_data});
    // console.log(output);

$(“script.template”).html() is creating the function to ask the underscore.js file for the HTML output code, and then giving it to the var tpl_func. var tpl_data is making our [variable] from step #2 either thumbnail or largeimg. They replace thumbnail or largeimg with the filenames mainimg_01.jpg, thumbnail_01.jpg and so on. var output is using our tpl_func function with the tpl_data as an argument, and then it appends the output code to the HTML.

you can see a DEMO here.


你的電子郵件位址並不會被公開。 必要欄位標記為 *

你可以使用這些 HTML 標籤與屬性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>