Ben’s LEARNING UNDERSCORE.JS

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="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></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">
  <ul>
    <% _.each(rc.imgItems, function(item){ %>
      <li>
        <div>
          <a href="images/<%- item.largeimg %>" >
            <img src="<%- item.thumbnail %>" width=200 height=200 />
          </a>
        </div>
      </li>
    <% }); %>
   </ul>
</script>

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.

<script>
    var tpl_data = {
        imgItems:[
            {
                largeimg:"mainimg_01.jpg",
                thumbnail: "http://3.bp.blogspot.com/-TRoudzX8VEU/ToR9u-ITjFI/AAAAAAAABv8/Dl8w3Id-_Qw/s200/free-rounded-star.png"
            },
            {
                largeimg:"mainimg_02.jpg",
                thumbnail: "http://www.snowfoxsoft.com/images/youtube1.jpg"
            },
            {
                largeimg:"mainimg_03.jpg",
                thumbnail: "http://cdn.appstorm.net/mac.appstorm.net/files/2010/05/freeApps-preview1.jpg"
            }
        ]
    };

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

$(“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>