JavaScript Handlebars Templates with Partials

Intro
In a previous blog post I provided the basics for creating an HTML template using the handlebars JavaScript library. In that post, I stuck to a very basic template. This time I will kick it up a notch and cover partials. You might be asking “What do I need partials for?” and you asking gives me a way to start explaining. So thanks for asking.

Let’s say you are making several templates from some data that is similar, but not identical. For example, sports leagues. Sports leagues are very similar in how they are composed, but not always identical. Some leagues call the major split conferences others call them leagues. Inside of a league there might be divisions; who knows. But at some point, we get to a level where it’s a single team, and we want all teams to have the same visual representation. This is where the handlebars partial comes in to play. I can make a team template, and use it any other template I want. All I have to do is register that partial with the handlebars library, then reference the partial in my template, and BOOM!, I have the same look across all sports leagues, conferences, divisions, whatever.

For now, I am focusing on one league (the NHL), so each team object has the name of the team, the location, the conference, and the division. I want each team to have the same look, so I am going to make a team template.

<script id="team-template" type="text/x-handlebars-template">
    <div class="teamDiv">
        <h3>
            {{location}} {{name}}
        </h3>
    </div>
</script>

Yes, that template is pretty basic and, for the moment, could go in line with the rest of my template, but if later on I make the template more complex, or I change to have the teams separated out by the conference/division, or I add more sports, I might end up with duplicated code.

Now that I have made my partial, it needs to be registered before it can be used. That is easy to do, and looks like this:

Handlebars.registerPartial("teamTemplate", $("#team-template").html());

Finally, once I have told the Handlebars engine about the template, I can use that partial in other templates. That notation looks like this:

{{> teamTemplate}}

Anywhere that appears in a handlebars script, my partial will be used.

My full template looks like so:

<script id="sports-template" type="text/x-handlebars-template">
    <div id="sport-list">
        {{#each leagues}}
        <div id="league-accordion" class="panel-group">
            <div class="league-header">
                <h1>{{{name}}} ({{acronym}})</h1>
            </div>

            <h3>Founded {{{founded}}}</h3>
            <div class="panel panel-default">
                {{#each teams}}
                {{> teamTemplate}}
                {{/each}}
            </div>
        </div>
        {{/each}}
    </div>
</script>

When I combine all that with my data, I get something like:

<div id="league-accordion" class="panel-group">
    <div class="league-header">
        <h1>National Hockey League (NHL)</h1>
    </div>
    <h3>Founded 1917</h3>
    <div class="panel panel-default">
    <div class="teamDiv">
        <h3>
            Colorado Avalanche
        </h3>
    </div>
    <div class="teamDiv">
        <h3>
            Chicago Blackhawks
        </h3>
    </div>
    <div class="teamDiv">
        <h3>
            Columbus Blue Jackets
        </h3>
    </div>
    <div class="teamDiv">
        <h3>
            St. Louis Blues
        </h3>
    </div>
    <div class="teamDiv">
        <h3>
            Boston Bruins
        </h3>
    </div>
    <div class="teamDiv">
        <h3>
            Montreal Canadians
        </h3>
    </div>
    <div class="teamDiv">
        <h3>
            Vancouver Canucks
        </h3>
    </div>
    <div class="teamDiv">
        <h3>
            Washington Capitals
        </h3>
    </div>
    <div class="teamDiv">
        <h3>
            Phoenix Coyotes
        </h3>
    </div>
    <div class="teamDiv">
        <h3>
            New Jersey Devils
        </h3>
    </div>
          ...      
    </div>
</div>

The power of this becomes more obvious as I try to sort my data with the user helpers…..in my next blog.

Review: Dave Fancher’s “The Book of F#”

This book is fantastic! I had little F# experience going into this book and found the basics of the language easy to understand and fun to read. Dave does an excellent job explaining F# from syntax, types, and its functional nature all the way through complex topics like quoted expressions and asynchronous programming. The occasional Dr. Who reference is sure to catch the eye in his exciting code samples. As a C# developer I really appreciated Dave’s chapter that focused on comparing F#’s APIs to C#’s. I feel confident in adding F# to any of my pre-existing C# projects right away. One thing that I found very intriguing was Dave’s focus on using F# for regular application development not just math! F# is not just a niche language for the scientific world, but is a way to help develop extremely testable and reliable code in everyday applications.

I highly recommend Dave Fancher’s “The Book of F#” to every .NET developer. Even if the developer does not adopt F# the lessons taught by the language are invaluable and will make them a better .NET developer in whichever language they use.

ASP.NET MVC5 + Twitter Bootstrap

Creating an ASP.NET MVC 5 Project

Model-View-Controller (MVC) is a software architectural pattern that divides software application into three parts.
Model consists of the business logic and functions.
View is the representation of the information. These information can be illustrated through graphs or charts or any of the user interface that the user interacts with.
Controller receives input from view and model.

1. Visual Studio -> New -> Project -> Under Web -> ASP.NET Web Application
2. Choose MVC template — this will create a default template with MVC folders.
Another template is Web API which will add API folder for REST HTTP calls.
ChoosingWebApi
3. Run the app to make sure it’s compiling and building properly.

Twitter Bootstrap 3 Discovery

What is Twitter Bootstrap? Twitter Bootstrap is an open-source tool that helps in creating websites or web applications. This tool includes pre-developed HTML and CSS templates for arranging html components (Grid-System), forms, buttons, charts, and other navigation components that we normally see in a responsive web application.

Some PROS of Twitter Bootstrap:

  • CONSISTENCY
    Who would not want to see a consistent font and style within a web page? Both developers and users would want to see a consistent flow in a project, so Twitter Bootstrap was built to avoid a confusing layout flow in every web page that users will interact.
  • RESPONSIVE
    Whether it is a huge desktop, a really small mobile screen or a phone with a size like a tablet, Twitter Bootstrap got it covered! This tool is developed to have a responsive layout that caters to all the different screen sizes that any user may have.
  • LATEST AND GREATEST
    Twitter Bootstrap was made by really great developers who used the latest libraries out there: CSS3, HTML5, JQuery… etc. The CSS was developed using LESS platform that allows using variables, mixins, functions inside the CSS page to make CSS more themable and extendable.

By default, MVC5 is using the Twitter Bootstrap template by default. That means, the bootstrap.min.js and bootstrap.min.css are already inside the project and we do not need to download it from Twitter Bootstrap’s webpage to use it’s styles.

Grid System

  • Twitter Bootstrap makes the page responsive to phone/tablet/desktop by adding the viewport meta tag:
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
  • Twitter Bootstrap’s grid system scales up to 12 columns.
    This means that all the columns with .col-md-* should add up 12. Any columns after the 12th will be stacked underneath the first 12.
  • Rows are placed inside a class .container for proper alignment.
    <div class="container">...</div>
    
  • Use class .row to create horizontal column groups.
  • Columns are created specifying the number that can add up to twelve. For example, four proportionally sized columns would be: four div with class .col-md-3
    XS = Phones, SM = Tablets, MD = Desktops, LG = Large Desktops
  • GridSystemTable

NOTE: As the browser widens, the smaller-sized classes gets overwritten. As the browser contracts, the larger classes are overwritten.

<div class="row">
    <div class="col-xs-6 col-md-6 col-sm-6">col-xs-6 col-md-6 col-sm-6</div>
    <div class="col-xs-6 col-md-6 col-sm-6">col-xs-6 col-md-6 col-sm-6</div>
</div>
<div class="row">
    <div class="col-xs-4 row-grid">col-xs-4</div>
    <div class="col-xs-4 row-grid">col-xs-4</div>
    <div class="col-xs-4 row-grid">col-xs-4</div>
</div>
<div class="row">
    <div class="col-md-3">col-md-3</div>
    <div class="col-md-3">col-md-3</div>
    <div class="col-md-3">col-md-3</div>
    <div class="col-md-3">col-md-3</div>
</div>
<div class="row">
    <div class="col-xs-8 col-md-8 col-sm-8">col-xs-8 col-md-8 col-sm-8</div>
    <div class="col-xs-4 col-md-4 col-sm-4">col-xs-4 col-md-4 col-sm-4</div>
</div>

Other Good Stuff…

Offsetting columns

To move columns to the right, use “.col-*-offset-*”. The first * depends on the screen size which could be written as “.col-xs-offset-, .col-md-offset-, or .col-sm-offset-”. The second * increases the left margin of column by * columns. For example, “.col-md-offset-4″ moves that column over four columns.
offset
As we can see on this example, we could combine the class names “.col-md-4″ and “.col-md-offset-3″ which defines the width of the column then offsets the column to 3 columns (-offset-3).

Like the grid system example, the offsets follow the 12-column way of how the columns are arranged. An example would be doing “.col-md-4″ followed by a div with “.col-md-4 .col-md-offset-4″. Where will the second div be?
nested-offset
So, since the position of the second div (without the -offset-4) is beside the first div, the offset made it so it moved another 4 columns over.

<div class="row">
    <div class="col-md-4">.col-md-4</div>
    <div class="col-md-4 col-md-offset-4">.col-md-4 .col-md-offset-4</div>
</div>
<div class="row">
    <div class="col-md-3 col-md-offset-3">.col-md-3 .col-md-offset-3</div>
    <div class="col-md-3">.col-md-3</div>
</div>

Nesting columns

Inside the .row, we can add a set of .col-md-* inside of an exisiting .col-md-*. To visualize it properly…
nested-row

<div class="row">
    <div class="col-md-9">
        1st row .col-md-9 (Parent Row)
        <div class="row">
            <div class="col-md-6">
                Nested 2nd row .col-md-6
            </div>
            <div class="col-md-6">
                Nested 2nd row .col-md-6
            </div>
        </div>
    </div>
</div>

For this example, the parent row (with a class .col-md-9) has a 9 column-width. Since the next row is nested (with 2 .col-md-6) that add up to 12-columns, their TOTAL WIDTH will only extend up to 9 columns (not 12), but they will be evenly divided because both of them add up to 12 columns.
What I mean by that is…
NestedAndNonNestedRows

<div class="row">
    <div class="col-md-9">
        1st row: .col-md-9
        <div class="row">
            <div class="col-md-6">
                2nd row (Nested): .col-md-6
            </div>
            <div class="col-md-6">
                2nd row (Nested): .col-md-6
            </div>
        </div>
    </div>
</div>
<div class="row">
    <div class="col-md-6">
        (Not Nested) .col-md-6
    </div>
    <div class="col-md-6">
        (Not Nested) .col-md-6
    </div>
</div>

IMPORTANT: Nested rows (even when the column-set adds up to 12 columns) follow the max width of the parent row unlike a non-nested row that can span out to 12-column width.

Push and Pull Columns (Column Ordering)

We use the modifiers .col-md-push-* and .col-md-pull-* to change the order of the grid columns.

<div class="row">
    <div class="col-md-9 col-md-push-3">1st column (col-md-push-3)</div>
    <div class="col-md-3 col-md-pull-9">2nd column (col-md-pull-9)</div>
</div>

This code results to:
pushpullTB

For this example, we can see that we pushed the 1st column to 3 columns to the right and pulled the 2nd column 9 columns to the left. Since the columns are also 9 and 3 column-width respectively, they just switched places.
IMPORTANT: In other words, we use -push- and -pull- to re-organize our column positions. Unlike offsets, when we “push” a column, it does not affect the position of any other column beside it. For example, if there are 2 columns, and only the first column has a “-push-*” class, the 2nd column will stay in the same place and will not be pushed to the right. Offset, on the other hand, pushes everything to the right of the column that has the -offset-* class.

References:

Twitter Bootstrap 2.3.2
Twitter Bootstrap 3

Android Development with Android Studio

Click here to download code and sample project

Currently, developing mobile applications is one of the most popular environments to program. So, I decided to go ahead and take a step back into the world of Java to create an Android app. I went ahead and decided to give Google’s IDE, Android Studio, a try during this process. The IDE, which is based on IntelliJ IDEA, is still in early access preview though, but already looks quite promising.

To get started I went ahead and downloaded the Android Studio. As a preface, Android Studio requires at least JDK 6 installed before beginning. The entire installation process may take a while if the JDK needs to be installed first. Also, I would highly recommend downloading Genymotion as an Android Emulator replacement since the one on Android Studio is extremely slow. As for learning how to develop an Android application, the tutorial on Android’s site works quite well located here.

So, during this project I decided to port my coworkers TicTacToe concept into Android. The game is similar to regular TicTacToe, except the game is expanded into a 3×3 grid of TicTacToe games. Each individual game that is won is considered a marker for the overall game. There is also a bit of strategy that was added to force the player to consider where their next move should. Needless to say, it is quite an interesting take on TicTacToe and I encourage you to try it.

Since I am coming from a C#/WPF world I am going to bring over some of the concepts of MVVM into this architecture. If you are not familiar with MVVM it is simply a way to decouple business logic from the UI. This way the UI can change however it needs to while keeping the main logic the same.

To get started, open up Android studio and create a new project. When created you can see there is already a pretty verbose folder structure created for a default project.

Project ViewLet us start off with adding basic information for our application by looking into the AndroidManifest.xml. In here I will simply add a title for our app by setting the  android:label property. Then to include an app icon, I must include an image into each of the res/drawable-xxxx folders with the image resized appropriately. Here is a rough break down of the dimensions:

    • drawable-ldpi (120 dpi, Low density screen) - 36px x 36px
    • drawable-mdpi (160 dpi, Medium density screen) - 48px x 48px
    • drawable-hdpi (240 dpi, High density screen) - 72px x 72px
    • drawable-xhdpi (320 dpi, Extra-high density screen) - 96px x 96px
    • drawable-xxhdpi (480 dpi, Extra-Extra-high density screen) - 144px x 144px

From <http://stackoverflow.com/questions/5350624/set-icon-for-android-application>

After that we will go back to our manifest file and set the android:icon to our new app icon. Once we compile the app successfully and attempt to run though, the studio brings up the Device Manager to choose an emulator. If you decided to install Genymotion (which I still highly recommend), run it and add a new device to emulate. Once added, select the new device and click play. You will see the device represented in a new window and back in Android Studio when you look in the Device Manager you should see your new emulator.

2014-04-16 15_16_17-Choose Device

So selecting our new emulator we’re able to start running our application. Great, now let us start developing our custom View. I created a MiniBoardView class that extends View which will handle the drawing of the board, markings, and whether the board is in a playable, win, or draw state. You can download the project and view the class file to see all the logic that goes into place, but here are a few main points:

  • We will need to create a custom Paint object that handles the drawing to the screen
  • Any new action that can apply to the board needs a call to invalidate to update the UI
  • To view the control in the designer, certain logic will need to get ignored on rendering. This can be done by doing a check on isInEditMode
  • For all our rendering purposes, make sure to override the onDraw method

Once our view is ready for usage, I went ahead and started implementing the business logic. After setting up the base Model-ViewModel classes I went ahead and tried out my first hit test logic.

First Hit Test Response

Now that the basis for our application is done, the rest is simply filling out the logic for our game.  Here is our final result:

Final Output

This should go without saying, but Android Studio is not even at version 1.0. Because of that the IDE is quite unstable. This led to many different frustrations throughout the learning process. Sometimes I would have to restart Android Studio simply because it refused to successfully build anymore. Another peculiar issue I ran into was opening up my project one day, running my app, and suddenly view this:

2014-04-16 15_27_16-Genymotion for personal use - Galaxy S4 - 4.3 - API 18 - 1080x1920 (1080x1920, 4

What happened to the sizes of my boxes? Did the logic change? No. Did I mistype something? No. Maybe restarting will help? No. I tried many different solutions and even recoded much of the design to no avail. Out of frustration I stepped away for a while and came back to find everything was back to normal. Never saw this problem again. Also, I use to update the product periodically as well until one update caused my whole project to fail. Several hours of snooping online pointed me to updating certain gradle files to get my project working again. Needless to say, I ceased doing that for the rest of my development.

Overall, I enjoyed the development process going back into Java and using Android Studio. I did not take full advantage of what the Android stack has available but I look forward to attempting another project using this IDE.

The Association for Competitive Technology

I am in Washington DC to meet with my elected officials and educate them about the growing mobile economy and tech innovation. I’m here with Emilie Hersh from.IK.

I have served the Association for Competitive Technology (ACT) since 1998 and it’s an honor to be a part of this amazing group.

The group is made up of leading entrepreneurs from across the country to participate in the Association for Competitive Technology Washington Fly-In. Around 50 of us, have descended on the nation’s capital to help lawmakers in the Congress and Senate recognize the incredible impact that small technology companies are having on our nation’s economy.

I have travelled to Washington DC (with some fly fishing in West Virginia before) to alert lawmakers about important issues including intellectual property and patent reform, data security and privacy, and regulatory obstacles to growth. We also look to areas where technology and policy can combine to meet the needs of industry and consumers.

These are all important issues that the federal government is facing. The outcomes really matter to me and that is why I will continue to try to make sure my voice is heard. Hopefully, an informed Congress will allow companies like InterKnowlogy and Actus to continue to flourish.

ACTOnline – Fly-In 2014 – The Importance of Being Active

It’s a great Monday on the East Coast!! I am currently in Washington, D.C. to meet with my elected officials and educate them about the growing mobile economy and tech innovation.

I’ll be joining up with leading entrepreneurs from across the country to participate in the Association for Competitive Technology Washington Fly-In. Around 50 of us will descend on the nation’s capital to help lawmakers recognize the incredible impact that small technology companies are having on our nation’s economy.

More than three-quarters of the most successful companies in the mobile software industry are small businesses – and apps are now a $68 billion marketplace. No one talked about apps six years ago, but now a whole ecosystem has emerged creating jobs for software developers, engineers, graphic artists, marketing professionals, and administrative personnel.

I am here in Washington to alert lawmakers about important issues including intellectual property and patent reform, data security and privacy, and regulatory obstacles to growth. We also look to areas where technology and policy can combine to meet the needs of industry and consumers.

These are all important issues that the federal government is facing. The outcomes really matter to me and that is why I’m making sure my voice is heard. Hopefully, an informed Congress will allow companies like ours to continue to flourish.

It’s an exciting time, and we can all make a difference – letting our voices be heard, and taking action to ensure our future. Join us!!  #ACTFlyIn

DVLUP Day San Diego – Intro to WinPhone Dev and App Studio Materials

Thank you so much to those who attended my session today! It was awesome. All of my materials were websites and Visual Studio project templates. You can find them here:

We also learned about Windows Phone AppStudio.

If you have any questions feel free to contact me! You can find me on twitter: @dannydwarren or here in comments.

Basic Javascript Templates with Handlebars

I have recently worked on a project using Javascript with Handlebars as a templating engine. I do not claim to be a Handlebar, or Javascript, expert, I am just making note of what I have learned for future reference and maybe something I write here will benefit someone else who trying to get started with Handlebars.

I have made a simple little example project with some sports themed data. My data is a collection of sports leagues. Each league has a Name, an acronym, the year it was founded, and can have a collection of teams. Each team has a city, a name, and a division. The structure in Json form is this:

var sportData = {
    league: [
        { name: "National Hockey League", acronym: "NHL", founded: 1917, },
	{ name: "Major League Baseball", acronym: "MLB", founded: 1869, },
        { name: "National Basketball Association", acronym: "NBA", founded: 1946, },
        { name: "National Football League", acronym: "NFL", founded: 1922, },
        { name: "Major League Soccer", acronym: "MLS", founded: 1993, },
    ]
};

In theory this is something that is returned from an API, but for the purpose of this small example, in code will work. So the question is, how can I easily display this data? The answer that I am covering in this blog is……Handlebars. Shocker, right?

So here is my simple Handlebars template to plop that data into the web page for me.

<script id="sports-template" type="text/x-handlebars-template">
    <div id="sport-list">
        <ul>
            {{#each league}}
            <li>
                <label>{{{name}}} ({{acronym}}) [Founded {{{founded}}}]</label>

            </li>
            {{/each}}
        </ul>
    </div>
</script>

So let’s break this down. This really is just HTML with some handlebars bits injected. So I have a container div I call sport-list. This literally is just a wrapper div that I choose to put. It is not used for anything at the moment. Next I have a <ul> to start my list. Just below that, there is the first bit of handlebars notation, which is {{#each league}}. This is essentially a foreach that is seen in many other languages. So {{#each league}} will look for an object called league within the current data context. Then, for each object within the league object, handlebars will repeat the chunk of code until the matching {{/each}}. Inside of the each, there is an <li> just to make each entry its own list item, then a boat load of curly braces. The first handlebars bit is {{{name}}}, which tells handlebars to put whatever is in the object called “name” there. Then {{{acronym}}} tells handlebars to put whatever is in the object call “acronym” in that place. I am sure that you can now guess what {{{founded}}} does. If any of that data is missing, handlebars essentially leaves it blank.  The last bit of important information is the id on the script tag. That will be what is given to handlebars to let it know what template to use.

Before you can use a handlebars template on a webpage, it needs to compiled. To do that, we have to call “Handlebars.compile()” and pass in the id of the script that you want compiled, in my case that is “sports-template.” I have chosen to put the actual Handlebars.compile call inside of an object called “handlebarsSample” that will also be used to hold as much of the handlebars related javascript as possible. “handlebarsSample” looks like this:

var handlebarsSample = function () {
    function compileTemplate(scriptId) {
        if (scriptId[0] != "#") {
            scriptId = "#" + scriptId;
        }

        return Handlebars.compile($(scriptId).html());
    }

    function registerPartials() {
        //No partials right now
    }

    function registerHelpers() {
        //No Helpers right now
    }

    return {
        compileTemplate: compileTemplate,
        registerPartials: registerPartials,
        registerHelpers: registerHelpers,
    };
}();

To explain this, I will start at the top. The first thing I do is define an object called “handlebarSample,” which is just a function used to house other objects. Currently, those three objects are registerPartials, registerHelpers, and compileTemplate. The two registers are not currently being used because my sample is too simple to need them yet, so I am not going to explain them. They are just placeholders at the moment. compileTemplate, however, is used. That is where I am actually calling the Handlerbars.compile function. This allows me to do some validation or error checking of the script Id that I want to compile. My case I am just making sure that I have the needed “#” that jquery uses to find Ids in the DOM. If the first character is not a “#” put one, then pass that to the compile function, which is returned from this function to where ever the call to it was made.

So now I have data. I have made a template. I have compiled that template. But I have nothing showing up on my webpage yet.  That is because we have not yet plugged the data and template together, nor have we injected the result. The first step is to actually compile the template.

var sampleTemplate = handlebarsSample.compileTemplate("sports-template");

Then I want to take that result, plug the data into, and put it somewhere on the page.

$('#sample-div').append(sampleTemplate(sportData));

Lets work inside-out for this. The sampleTemplate(sportData) is where I plug my data into the handlebars template. Then I use a basic jquery selector to grab the appropriate div, then I just append the results that div which gives the output of:

National Hockey League (NHL) [Founded 1917]
Major League Baseball (MLB) [Founded 1869]
National Basketball Association (NBA) [Founded 1946]
National Football League (NFL) [Founded 1922]
Major League Soccer (MLS) [Founded 1993]

That is the very basics using handlebars. There is a more I plan to cover, including partials and helpers in future blogs, hopefully soon (no promises).

For the full source look at these two files.
SportsLeagues.html
handlebarsSample.js