• Using Handlebars Templates With Backbone and Browserify

    browserify_logo

    While working on a recent side-project, I ran into some trouble implementing Handlebars templates for my use in my backbone views when using Browserify for my dependency management. If you’ve run into similar issues, here’s a quick breakdown of what you’ll need to do to get up and running again:

    1. Install Hbsfy

    In order to precompile the templates for use in your app, you’ll need to install hbsfy and include it in your gulpfile. For the record, I have no idea what the hell that’s supposed to stand for but I like to imagine it being short for “Handlebars Sci-Fi” but spelled in the same way as the terrible TV network. Here’s a snippet from my gulpfile for you to use as a starting point.

        var gulp,
            browserify,
            del,
            gulp,
            hbsfy,
            sass,
            source,
            sourcemaps;
    
        gulp = require('gulp'); // Include gulp
    
        // Include our plugins
        browserify      = require('browserify');
        del             = require('del');
        hbsfy           = require("hbsfy"); // <---- THIS RIGHT HERE
        sass            = require('gulp-sass');
        source          = require('vinyl-source-stream');
        sourcemaps      = require('gulp-sourcemaps');
        //---
    ...
    

    Apply Hbsfy During the Bundle Process

    Once you’ve included Hbsfy, you’ll need to apply it as a transformation during the bundle() process:

    ...
        gulp.task('compile', function () {
            var options;
    
            options = {
                debug: true,
                paths: [
                    './node_modules',
                    './src/app/'
                ]
            };
    
            hbsfy.configure({
                extensions: ['hbs']
            });
    
            browserify('./src/main.js', options)
                .transform(hbsfy)
                .bundle()
                .pipe(source('app.min.js'))
                .pipe(gulp.dest('build/public/assets/js'));
        });
    ...
    

    The one thing to note in the above snippet is the call to hbsfy.configure where I am simply telling hbsfy (I seriously want to know what that stands for) that my template files will all end in .hbs. You can substitute in whatever file format you’re using for your templates.

    3. Include the Template in the Same File As Your Backbone View

    Once you’ve got your gruntfile configured properly, you can safely start using Handlebars templates in your Backbone views…almost. You still need to include them. It’s rather straightforward:

    (function () {
        'use strict';
    
        var User,
            Users,
            Handlebars,
            template,
            Backbone;
    
        Backbone = require('backbone');
        User = require('entities/user');
        Users = require('collections/users');
        Handlebars = require('handlebars');
        template = require('./search-full.hbs'); // <!-- RIGHT HERE
    ...
    

    4. Override the Render Method of Your View and Call the Template

    ...
        module.exports = Backbone.View.extend({
            className: '.form',
            el: '#app',
            events: {
                'keypress .search .field': 'submitSearch'
            },
            initialize: function () {
                this.render();
            },
            render: function () { // <!-- OVERRIDDEN
                this.$el.html(template());
                return this;
            },
    ...
    

    For the record, I’m not sure if this is the way to do this. However, I tried simply setting the value of the template property on the view and it didn’t work. If you know of a better way, feel free to leave a comment.

    Wrapping Up

    Well, I hope this eased someone’s frustrations out there. If it did or if you know of a better approach to this problem, please let me know in the comments below.

  • 5 Questions to Ask Yourself When Using Recursion

    Recursion

    Recursion can be a tough concept to grasp regardless of the language you decided to program in. In order to help developers who find themselves struggling with the concept (myself included), I’ve broken down the concept into five simple questions you’ll need to answer in order to write solid recursive functions (inspired by the folks over at CodeCademy).
    Read more

  • How to Make Gulp Copy a Directory AND Its Contents

    gulp-2x

    I just got done switching one of my side-projects over to Gulp for the build process and I kept struggling with how to copy multiple folders from the src directory to the build directory in such a way that the directory’s contents and its original folder structure are preserved. Basically, I was trying to achieve this:
    Read more

  • How to Exclude Layout Files When Rendering Templates With Node.js and Express

    I struggled with this for a good half-hour and I figured I’d share in case anyone else ran into this issue. Long story short, I needed to return an HTML fragment for a particular ajax request from the app (in this case, search results) but the response always included the layout file I configured for the app:

        hbsEngine = expressHbs.create({
            extname: 'hbs',
            defaultLayout: 'layout.hbs',
            helpers: {
                formatDate: function (date, format) {
                    return moment(date).format(format);
                }
            }
        });
    

    Read more

  • How to Parse Responses From the StackExchange API Using Node.js

    Currently, I’m working on a small side project that involves parsing the wiki entries for given tags on StackOverflow. Without going into a ton of boring detail, the task I was trying to complete can be broken down thusly:

    1. Make a request for the wiki entries of one or more tags from the SE API.
    2. Show that data in a Handlebars template
    3. Profit

    Read more

  • Formatting Dates Using Moment.js, Handlebars, Express, and Node.js

    For those of you out there that may be struggling with this, here’s a quick breakdown of how to format dates using moment.js, handlebars, express, and node.js. This post assumes you have the following packages installed in your express app:

    1. Express3 Handlebars (link)
    2. Moment.js (link)

    Once you’ve included these packages in your app.js file, you’ll need to set up handlebars like so:

    ...
    app = express();
    hbsEngine = expressHbs.create({
        extname: 'hbs',
        defaultLayout: 'layout.hbs',
        helpers: {
            formatDate: function (date, format) {
                return moment(date).format(format);
            }
        }
    });
    
    // view engine setup
    app.set('views', path.join(__dirname, 'views'));
    app.engine('hbs', hbsEngine.engine);
    app.set('view engine', 'hbs');
    ...
    

    You can ignore the extname and defaultLayout configs incase you want to use the default values that handlebars sets for you for the extension and layout file name. The important thing to note is the helpers object. Basically, it’s the equivalent of the registerHelpers method in the JS version of Handlebars. In this example, I’m create a formatDate method that takes in a date and “format“ string and returns a formatted date via moment.js.

  • Helpful Tools For Web Developers: CodeWars.com

    6054331276_db66692527_b

    The ability to solve new problems efficiently is the hallmark of a good developer. When interviewing dev candidates, I don’t necessarily look for their experience with a particular framework or API. Most of the time, I’m looking at how they go about approaching a problem they’ve (most likely) never seen before. You’ve probably encountered questions like “write a function that finds x number in the Fibonacci sequence” or the ubiquitous “FizzBuzz” puzzle. These questions and others like it are designed to give the interviewer insight into how you think about a problem and the kinds of solutions you’ll come up with.
    Read more

  • Helpful Tools for Web Developers: CSS Arrow, Please

    cssarrowplease

    Recently, I’ve discovered that making css arrows (see image above) is a huge pain in the ass. Luckily, there’s a tool to make it easy for you: CSS Arrow, Please (I added the comma because it was driving me nuts). I highly recommend you check it out if you need an arrow for UI elements such as speech bubbles, tooltips, or popovers.

  • CodePen: Dropdown Menu

    I made a simple, static dropdown menu widget that’s meant to act as a template for dropdowns you need to create.

    See the Pen Lkgzv by Levi Hackwith (@opnsrce) on CodePen.

    Currently, it’s not animated but feel free to fork it.

  • A Quick Visual Guide to Relative Positioning in CSS

    medium_4365152223 (2)

    Getting your head around positioning elements in CSS can be very confusing. When I first started doing front-end web development, I would often end up spending hours trying to figure out why one element or another was refusing render where I thought it should. Nine times out of ten, the problem usually had something to do with the surrounding elements and what the value of their position attribute happened to be.

    In order to help new developers understand how relative positioning works in CSS, I put together a quick visual demonstration:

    See the Pen bgHAJ by Levi Hackwith (@opnsrce) on CodePen.

    The box labeled “5” is absolutely positioned zero pixels from the right side of its parent container (by default, container 4).

    When you click on one of the checkboxes, the corresponding container div’s position property gets set to static (the default value). If you click on the checkbox labeled “Disable Level 4″, you’ll notice that the “5” box jumps from the right of box 4 to the right of box 3. This is because, by setting 4’s position to static instead of relative, you are telling box 5 that 4 is no longer the parent container. Confused? I was too. When we look at the nested nature of HTML, we would assume that the “parent container” of an element is the nearest element that contains another element. In our case, the parent of 5 would be 4. However, the browser sees things a little different. It defines a parent element as the nearest element that contains another element that also has its position element set to relative. By changing the position attribute of a parent element, you’re forcing the browser to look for the next nearest element with a relative position. Notice how, if you recheck the checkbox, the 5 box jumps back into place.

    Hopefully the clarifies things regarding relative positioning in CSS. If you have any questions or feedback, please leave a comment.

    photo credit: atzu via photopin cc