Skip to content

Instantly share code, notes, and snippets.

@funkybrain
Created November 21, 2012 00:00
Show Gist options
  • Select an option

  • Save funkybrain/4122123 to your computer and use it in GitHub Desktop.

Select an option

Save funkybrain/4122123 to your computer and use it in GitHub Desktop.

Revisions

  1. funkybrain created this gist Nov 21, 2012.
    71 changes: 71 additions & 0 deletions JavaScript: Handlebars
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,71 @@
    <!doctype html>
    <html>
    <head>
    <meta charset=utf-8>
    <title>Handlebars</title>
    <style>

    span {
    color: red;
    font-size: 0.5em
    }

    </style>
    </head>
    <body>

    <ul class="tweets">
    <script id="template" type="text/x-handlebars-template">
    {{#each this}}
    <li>
    <h2>{{fullName author}} - {{#if age}}<span>{{age}}</span>{{/if}}</h2>
    <p>{{tweet}}</p>
    {{#unless quote}}
    <h5>Author does not have a quote</h5>
    {{/unless}}
    </li>
    {{/each}}
    </script>
    </ul>

    </body>


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

    <script src="http://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.rc.1.js"></script>

    <script type="text/javascript">
    // always place code in SIAF to avoid creating global variables

    (function(){

    // create an object that is itself an array of objects
    var data =[
    {
    author: {first: 'Jeffrey', last: 'Way'},
    tweet: '30 days to learn jquery rocks',
    age: '27'
    },
    {
    author: {first: 'John', last: 'Wayne'},
    tweet: 'Rio Bravo was awseucj',
    quote: 'I kill for a living'
    }];

    // Helpers
    Handlebars.registerHelpre('fullName', function( author ){
    return author.first + ' ' + author.last;
    });

    // this returns a function
    var template = Handlebars.compile( $('#template').html() );

    // and then append it to your DOM
    $('ul.tweets').append(template(data));

    })();


    </script>
    </html>