Friday, December 19, 2014

Stop trying to add class structure to JavaScript

Recently, I read an interesting article titled The Two Pillars of Javascript, and one of the points in the article that I found interesting was the part about trying to create classes in JavaScript. Stop trying to create class structure in JavaScript? But, I thought classes and OOP are how we should be programming, plus classes are everywhere in .NET, Java and Ruby.

The article talks about how JavaScript is not like other languages and how we should embrace the "objects without classes" and "anonymous functions (Lambdas)" structure that it provides.

I only bring this up because after reading that article, I realized, that in Angular I'm unconsciously doing this already. With AngularJS you never use the "prototype" or "new" keywords, because your only registering objects or constructor functions.

Ok, lets step back, what are we talking about?
Here is how we create an object using class like functionality as shown in a previous post:
var Car = function(color) {
    this._wheels = 4;
    this._condition = 'good';
    this.initialize(color);
}
Car.prototype.initialize = function(color) {
    this._color = color;
    ...
};
Car.prototype.drive = function(speed) {};

//create a car and drive
var myCar = new Car(#bada55);
myCar.drive(90);

//and then extend Car and create a Truck
var Truck = function(color){
    this._type = 'pickup';
    this.initialize(color);
}
var tmp = Truck.prototype = new Car();
Truck.prototype.Car_initialize = tmp.initialize;
Truck.prototype.initialize = function(color) {
    this.Car_initialize(color);
    ...
};
Truck.prototype.tow = function(weight){};

And this works fine, but how can we do this using just objects and factory methods? The key method you will need is the extend method which we can borrow from jquery $.extend() or any other JavaScript frameworks. The extend method basically copies all the properties and methods from one object to another. You've probably used this to create copies of data objects already.

With this method we can do the same operation as above but with factory methods instead of fake classes. For the Truck object, we can just 'extend' and internal car object using the extend method.
function createCar (color) {
    var _color = color,
        _wheels = 4,
        _condition = 'good';
        
    return {
        getColor : function () { return _color; },
        setColor : function (color) {
            _color = color;
        },
        drive : function (speed) {}
    }
}
//and then extend Car and create a Truck
function createTruck (color) {
    var _car = createCar(color),
        _type = 'pickup';
    
    //here we can use our extend method to add new methods to truck
    return $.extend(_car, {
        getType : function () { return _type; },
        tow : function (weight) {}
    });
}

//now we can create a truck and drive
var myTruck = createTruck(#bada55);
console.log(myTruck.getType());
myTruck.drive(90);


One of the great things about this way is you can now have real private variables. There is no way to access _color and _wheels, unless you create getters and setters which is generally a good practice. We can even have private functions inside our factory methods. Here is a Wiki link to learn more about the Factory Method Pattern. This article only covers a small part of it.

How is this used in Angular? Every time you call a app.controller(), app.directive(), app.factory(), etc. you are supplying a factory method to create this object. Now, thinking this way, I wonder if controllers, directives, or services could be extended? Hmm, not sure, I'll have to do some testing.

Friday, November 7, 2014

AngularJS custom data table example

This is probably the first of many post on AngularJS since the project I'm on uses AngularJS for the front-end with a Java (Play framework) back-end. I don't know anything about Play (sorry) but I have picked up quite a lot of Angular in the last few months.

Feeling like I might be finally getting the hang of AngularJS, I wanted to do a post about the custom data table I just finished. Before You read more, if you want a pre-made component then I'd recommend ngTable. We actually used it for some of the work on this project. In some situation we ended up running into issues and just rolled our own. It seems that, with AngularJS, I often start using a pre-built solution and find myself in a hole with some functionality that the client requested and that wasn't originally part of the component, ugh.

So, this is just a place for you to start from in your project. This table directive will have 2 attributes, "ng-model" which will be the rows of data and "columns" which will be how you configure columns headers and what data to display.

Let start with a simple directive definition:
// customAngularTable.js
mainApp.directive('customAngularTable', function () {
    return {
        restrict : 'E', //this can only be used as a tag 
        replace  : true, //replace the html tag with out template
        require  : 'ngModel', //this directive has to have the attr ng-modal=""
        scope    : {
            ngModel : '=', //variable name will be the same on our scope object
            columns : '='
        },
        templateUrl : 'customAngularTable.tpl.html',
        controller : 'customAngularTableCtrl'
    };
});
The basic template will look something like this:
// customAngularTable.tpl.html
<div>
    <table>
        <thead>
            <tr>
                <th ng-repeat="col in columns" 
                    ng-click="applySort(col)">
                    {{col.label}}
                </th>
            </tr>
            <tr>
                <th ng-repeat="col in columns">
                    <input type="text" 
                           ng-model="filters[col.property]" 
                           ng-change="applyFilters(col)" />
                </th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="row in tableRows">
                <td ng-repeat="col in columns">
                    {{row[col.property]}}
                </td>
            </tr>
        </tbody>
    </table>
    
    <hr />
    <!-- We can just use a pre-built component to page since that 
            is beyond the scope of this tutorial -->
    <pagination ng-model="currentPage" 
                items-per-page="pageSize" 
                total-items="rowsTotal" 
                previous-text="&lsaquo;" 
                next-text="&rsaquo;">
    </pagination>
</div>
Which brings us the the fun part, the controller:
// CustomAngularTableCtrl.js
mainApp.controller('customAngularTableCtrl', function ($scope) {
    'use strict';

    /**
     * View Variables
     */
    $scope.tableRows = [];
    //- sorting
    $scope.currentSortColumn = null;
    $scope.currentSortOrder = '';
    //- filtering
    $scope.filters = {};
    // - paging
    $scope.currentPage = 1;
    $scope.pageSize = 10;
    $scope.rowsTotal = 1;

    /**
     * View Methods
     */
    $scope.applySort = function (columnToSortOn) {
        
        if($scope.currentSortColumn === columnToSortOn) {
            //user has clicked the same column, so we need to change sort order
            //we have 3 sorting states here to step through (asc,desc,'')
            $scope.currentSortOrder = ($scope.currentSortOrder === '') ? 
                'asc' : ($scope.currentSortOrder === 'asc' ? 'desc' : '');
            
            //if the previous operation set currentSortOder to blank, 
            //remove currentSortColumn
            if($scope.currentSortOrder === '') {
                $scope.currentSortColumn = null;
            }
        } else {
            //user has clicked a new column
            $scope.currentSortColumn = columnToSortOn;
            //step to first sort state
            $scope.currentSortOrder = 'asc';
        }
        
        //update view
        updateTableData();
        
    };
    
    $scope.applyFilters = function () {
        //reset current page to 1, se we don't filter out all the rows 
        //and display an invalid page
        $scope.currentPage = 1;
        
        //since, updateTableData will apply all the filters for us, 
        //we just need to re-call that method here.
        updateTableData();
    };

    /**
     * Watches 
     */
    //we'll need to setup a watch for ngModel so if it changes we update the view
    $scope.$watch('ngModel', function (newValue, oldValue) {
        //check if the value is defined and not null
        if(angular.isDefined(newValue) && newValue !== null) {
            //since we have a new array, update view
            updateTableData();
        }
    });
    
    //We need to watch currentPage so we can update the view with the current page
    $scope.$watch("currentPage", function (newValue, oldValue) {
        //check if the page really did change
        if(newValue !== oldValue) {
            updateTableData();
        }
    });

    /**
     * Private Methods
     */   

    function updateTableData () {
        //we will create a new array that we will fill with 
        //all the rows that should still bee in the view.
        var viewArray;

        //step 1: apply filtering on all the rows
        viewArray = $scope.ngModel.filter(applyFilters);
        
        //step 2: if the user has clicked a column, apply sorting
        if($scope.currentSortColumn !== null) {
            // using a getSorter function here allows you to use custom 
            // sorting if you want
            viewArray = viewArray.sort(getSorter());
        }
        
        //step 3: update pagination and apply
        $scope.rowsTotal = viewArray.length;
        // - current page is 1, based but our array is 0 based so subtract 1
        var pageStartIndex = ($scope.currentPage-1) * $scope.pageSize;
        // - page end index is either page size or whatever is left in the array
        var pageEndIndex = pageStartIndex + Math.min(viewArray.length, $scope.pageSize);
        // - splice view array to page start and end index's, and return the 
        //   page we want to view
        viewArray = viewArray.splice(pageStartIndex, pageEndIndex);
        
        //pass the ref to the viewArray to $scope and let angular refresh the html table
        $scope.tableRows = viewArray;
    }
    
    function applyFilters (row) {
        var allowed = true;
        
        //since we set ng-model on each input in the 2nd header row to filters[col.property] 
        //in the view, angular will auto-create a matching property key on the filters object 
        //and set it to whatever the user types into that input.
        
        //So, here we can loop through each property on the $scope.filters property and check
        //if the row should still be displayed.
        Object.keys($scope.filters).forEach(function (key) {
            var rowValue = row[key],
                filterValue = (angular.isDefined($scope.filters[key]) 
                                 ? $scope.filters[key] : "");
            
            //if this value is still allowed by other columns, 
            //test it with this filter value
            if(allowed && filterValue !== null) {
                //here is a good place to add custom filters based on this column. 
                //Ex. var column = lookupColumnFormKey(key);
                //    if(column.type === 'number')  
                //        allowed = numberFilter(rowValue, filterValue); 
    
                allowed = stringSearchFilter(rowValue, filterValue);
            }
        });
        return allowed;
    }
    
    function getSorter () {
        //Here you can return different sort functions based on $scope.currentSortColumn
        //Ex. if($scope.currentSortColumn.type === 'number) 
        //         return numberSorter($scope.currentSortColumn, $scope.currentSortOrder);

        return stringSorter($scope.currentSortColumn, $scope.currentSortOrder);
    }
    
    /**
     * Checks if value contains the chars that are in filterValue.
     */
    function stringSearchFilter (value, filterValue) {
        value = value.toString().toLowerCase(); //toString in case it's a number
        filterValue.toString().trim().toLowerCase();
        return (value.indexOf(filterValue) !== -1);
    }
    
    /**
     * Compares 2 rows as strings based on sortColumn.property.
     */
    function stringSorter (sortColumn, sortOrder) {
        return function (rowA, rowB) {
            var valueA = rowA[sortColumn.property],
                valueB = rowB[sortColumn.property],
                result = valueA.localeCompare(valueB);
            if(sortOrder === 'desc') {
                result *= -1;
            }
            return result;
        };
    }
});
I tried to add as many comments as I could so you can see whats going on here. Next would be how to implement this directive. You'll need to setup the columns array based on the data you want to display in the table.

Here is an example of how this is done:
mainApp.controller('AngularTableTestCtrl', function($scope) {
    $scope.rows = [
        { first : 'Sue', last : 'Davis', title : 'Web Developer', company : 'Infusion' },
        { first : 'David', last : 'Marks', title : 'Sales Rep', company : 'Walmart' },
        { first : 'Jake', last : 'Richards', title : 'Customer Service', company : 'Target' }
    ];
    $scope.columns = [
        { label : 'First Name', property : 'first' },
        { label : 'Last Name', property : 'last' },
        { label : 'Occupation', property : 'title' },
        { label : 'Company', property : 'company' }
    ];
});
And the actual directive html tag would be:
<custom-angular-table columns="columns" ng-model="rows"></custom-angular-table>
This will setup a very basic angular data table directive with filtering, sorting and paging that you can add to as needed. For paging I used Angular UI Bootstrap which works really nice. In the app I'm working on, I had to add custom filters, sorters and input fields into the table body with validation. Basicly, Excel in the browser :).

These files can be found on my GitHub repo https://github.com/jasonsavage/simple-angular-table.

Wednesday, June 4, 2014

Moving to Raleigh to work for Infusion

The time has come for me to pack my bags and move south. I've been in Pittsburgh, PA since I graduated from Edinboro University in 2003, and even a few years before college. Living and working in the burgh, I've gained a lot of experience and had the pleasure working with many really talented people. But, alas, the weather has finally gotten to my wife and me. Plus, my son is starting 2nd grade in the fall! and I fear that if we don't move soon, we'll never leave.

I was offered an Interactive Developer role with a big New York company called Infusion. Infusion is opening an office in Raleigh, NC and I'll be part of the many new hires for that team.

It saddens me to leave my current role with Moxie and move out of the city I've grown to love (and hate sometimes), but this is a great opportunity and I have to give it a try. Raleigh is a really pretty city and the area is booming with a lot of tech jobs, so we'll see how it goes... and hey, you can always move back, right?

Thursday, May 8, 2014

Date Strings from Twitter & Facebook Invaild? (IE & Safari)

Just learned about this yesterday. It seems that if you pass the date string that is returned from Twitter and/or Facebook to the javascript Date() constructor, in IE (and Safari), it shows it as an invalid date.

Twitter returns the "created_time" as something like this: Thu May 01 13:57:04 +0000 2014, which is shown as "Invalid Date" in IE.
    
    //created_time = Thu May 01 13:57:04 +0000 2014
    var date = new Date( jsonData.created_time );
    
    console.log( date.toString() );
    // = IE 9 & 10: 'Invalid Date' 
    // = Chrome:    'Mon May 05 2014 14:50:00 GMT-0400 (Eastern Daylight Time)'
    // = FireFox:   'Mon May 05 2014 14:50:00 GMT-0400 (Eastern Standard Time)'
    // = Safari:    'Mon May 05 2014 14:50:00 GMT-0400 (Eastern Daylight Time)'


For Facebook, the 'created_time' value is something like: 2014-04-17T12:59:04+0000, which is shown as "Invalid Date" in IE and Safari.
    
    //created_time = 2014-04-17T12:59:04+0000
    var date = new Date( jsonData.created_time );
    
    console.log( date.toString() );
    // = IE 9 & 10: 'Invalid Date' 
    // = Chrome:    'Thu Apr 17 2014 08:59:04 GMT-0400 (Eastern Daylight Time)'
    // = FireFox:   'Thu Apr 17 2014 08:59:04 GMT-0400 (Eastern Standard Time)'
    // = Safari:    'Invalid Date'


So, what fixed the problem, for now, was to do a little manipulation on the date string before it is passed it to the Date() constructor.
    
    //twitter = 'Thu May 01 13:57:04 +0000 2014'
    //facebook = '2014-04-17T12:59:04+0000'
    
    var created = facebook.created_time;

    if( isFacebook )
    {
        //this fixes the issue in IE and Safari, and still works in Firefox and Chrome even though they don't need it.
        created = created.replace(/-/g, '/').replace(/T/, ' ').replace(/\+/, ' +');
    }
    else if( isTwitter )
    {
        //this is only an issue in IE, so we can just do a quick test and fix the issue.
        if( navigator.userAgent.match(/MSIE\s([^;]*)/) )
            created = created .replace(/( \+)/, ' UTC$1');
    }

    var date = new Date( created );

Monday, May 5, 2014

Moving my SVG Animation to Canvas with EaselJS (follow-up post)

This is a follow-up to the previous post titled "SVG Animation With Clip Paths and Linear Gradients".

I was able you port the SVG animation over to the <canvas /> using EaselJS. It wasn't too bad, I was having a lot of trouble converting the SVG path data that was exported from illustrator, but that all changed when my co-worker found this site: http://www.professorcloud.com/svg-to-canvas/.

Here is the code I ended up with that re-created the animation from before:
function initCanvasHeart(canvasId)
{
    var stage       = new createjs.Stage(canvasId),
        goldRect    = new createjs.Shape(),
        greenRect   = new createjs.Shape(),
        blueRect    = new createjs.Shape(),
        goldMsk     = new createjs.Shape(),
        greenMsk    = new createjs.Shape(),
        blueMsk     = new createjs.Shape(),
        aa          = new createjs.Shape(),
        width       = stage.canvas.width,
        height      = stage.canvas.height,
        rectWidth   = width / 0.4;
    
    //create gold rect
    goldRect.graphics
        .beginLinearGradientFill(
            ["#FFC423", "#ffe191", "#FFC423"], 
            [0.4, 0.5, 0.6], 0, 0, rectWidth, 0)
        .drawRect(0, 0, rectWidth, height);

    goldRect.x = width-rectWidth;
    goldRect.cache(0,0,rectWidth, height);
    
    //add it to the canvas
    stage.addChild(goldRect);
    
    //create gold rect mask
    drawGoldStrip( goldMsk.graphics.beginFill("#000000") );
    goldRect.mask = goldMsk;
    
    //create green rect
    greenRect.graphics
        .beginLinearGradientFill(
            ["#6EB43F", "#b6d99f", "#6EB43F"], 
            [0.4, 0.5, 0.6], 0, 0, rectWidth, 0)
        .drawRect(0, 0, rectWidth, height);

    greenRect.x = width-rectWidth;
    greenRect.cache(0,0,rectWidth, height);
    
    //add it to the canvas
    stage.addChild(greenRect);
    
    //create green rect mask
    drawGreenStrip( greenMsk.graphics.beginFill("#000000") );
    greenRect.mask = greenMsk;
    
    //create blue rect
    blueRect.graphics
        .beginLinearGradientFill(
            ["#0083C8", "#7fc1e3", "#0083C8"], 
            [0.4, 0.5, 0.6], 0, 0, rectWidth, 0)
        .drawRect(0, 0, rectWidth, height);

    blueRect.x = width-rectWidth;
    blueRect.cache(0,0,rectWidth, height);
    
    //add it to the canvas
    stage.addChild(blueRect);
    
    //create blue rect mask
    drawBlueStrip( blueMsk.graphics.beginFill("#000000") );
    blueRect.mask = blueMsk;
    
    //add a layer to fix anti-aliasing in Chrome
    //- the mask in chrome was really pixelated compared to Firefox
    aa.graphics.setStrokeStyle(1, 1, 1, 2);
    drawGreenStrip( aa.graphics.beginStroke("#6EB43F") ).endStroke();
    drawGoldStrip( aa.graphics.beginStroke("#FFC423") ).endStroke();
    drawBlueStrip( aa.graphics.beginStroke("#0083C8") ).endStroke();
    aa.cache(0, 0, width, height);
    stage.addChild(aa);

    //add animations
    //using TweenJS that is part of EaselJS, we can create a simple repeating animation
    createjs.Tween.get(goldRect, {loop:true}).to({x: 0 }, 8000);
    createjs.Tween.get(greenRect, {loop:true}).to({x: 0 }, 8000);
    createjs.Tween.get(blueRect, {loop:true}).to({x: 0 }, 8000);
    
    //add an event listener to the internal ticker object to update the stage, 
    //otherwise we won't see the animation
    createjs.Ticker.addEventListener("tick", function( evt ) 
    { 
        stage.update();
    });
}

//these method were each generated by:
//http://www.professorcloud.com/svg-to-canvas/ 
function drawGreenStrip(g)
{
    g.moveTo(72.603,317.736);
    g.bezierCurveTo(71.87,316.727,74.997,320.537,72.603,317.736);
    g.bezierCurveTo(63.166,306.699,37.833999999999996,281.177,25.986999999999995,258.153);
    g.bezierCurveTo(-0.2700000000000067,207.12500000000003,-12.807000000000002,128.69500000000002,18.386999999999993,68.50900000000001);
    g.bezierCurveTo(38.157,30.357,72.942,6.779,118.972,0.328);
    g.bezierCurveTo(122.661,0.096,126.004,0,129.237,0);
    g.bezierCurveTo(180.874,0,240.743,26.183,251.61399999999998,145.724);
    g.lineTo(251.61399999999998,145.724);    g.bezierCurveTo(224.38899999999998,88.70599999999999,175.11599999999999,64.73599999999999,124.02599999999998,79.07799999999999);
    g.bezierCurveTo(96.53399999999998,86.79299999999999,72.37499999999997,114.35999999999999,60.29699999999998,146.654);
    g.bezierCurveTo(42.154,195.165,42.749,259.684,72.603,317.736);
    g.lineTo(72.603,317.736);
    g.closePath();
    return g;
}
   
function drawGoldStrip(g)
{
    g.moveTo(446.57,41.168);
    g.bezierCurveTo(423.02,17.616,391.671,4.649,358.286,4.649);
    g.bezierCurveTo(310.154,4.649,265.962,31.224,249.12099999999998,69.678);
    g.bezierCurveTo(253.90999999999997,82.536,257.52799999999996,97.475,259.68199999999996,114.699);
    g.bezierCurveTo(279.698,91.652,307.98499999999996,77.94200000000001,335.94599999999997,77.94200000000001);
    g.bezierCurveTo(358.849,77.94200000000001,379.186,87.218,391.736,103.39500000000001);
    g.bezierCurveTo(407.001,123.06200000000001,410.514,151.238,401.897,184.871);
    g.bezierCurveTo(389.59499999999997,232.871,326.669,325.246,243.46599999999998,359.457);
    g.bezierCurveTo(244.652,359.401,276.452,359.675,295.70399999999995,354.659);
    g.bezierCurveTo(372.371,334.659,441.4409999999999,277.092,459.236,242.862);
    g.bezierCurveTo(490.488,182.738,503.576,98.174,446.57,41.168);
    g.closePath();
    return g;
}
   
function drawBlueStrip(g)
{
    g.moveTo(239.213,444.16);
    g.bezierCurveTo(218.941,444.16,205.017,435.036,187.38,423.485);
    g.bezierCurveTo(183.989,421.265,180.448,418.94100000000003,176.668,416.56);
    g.bezierCurveTo(152.79000000000002,401.536,106.22800000000001,355.632,96.757,342.354);
    g.bezierCurveTo(67.397,301.205,44.056000000000004,186.868,72.796,146.81599999999997);
    g.lineTo(79.569,137.36399999999998);
    g.lineTo(80.349,148.96899999999997);
    g.bezierCurveTo(83.259,192.36699999999996,93.43100000000001,212.12199999999996,111.904,247.97699999999998);
    g.bezierCurveTo(137.74599999999998,298.144,195.71699999999998,360.70899999999995,248.362,371.56399999999996);
    g.bezierCurveTo(307.151,369.43199999999996,356.589,351.84,428.28700000000003,299.106);
    g.lineTo(428.28700000000003,299.106);
    g.bezierCurveTo(401.58700000000005,335.235,329.206,400.438,291.47900000000004,424.78499999999997);
    g.bezierCurveTo(277.495,433.81,258.921,444.16,239.213,444.16);
    g.closePath();
    return g;
}

SVG Animation With Clip Paths and Linear Gradients

One of our clients decided to update their logo from a circle to more of a heart. Currently, on the about us page of their website, they have a large version of their logo that spins slowly and when you rollover (or swipe/tap) each color in the logo information appears describing their products. One of our designers and I, sat down to discuss what we could do with a heart shaped logo because having it spin looked weird. We finally came up with a subtle shine effect on the colors, which at first, I thought would be easy since I've done it before with flash. I came to find out that there was a little more to it then I originally thought.

I decided to try the animation with SVG. After reading up on SVG graphics and animations, came up with the following which turned out great:




Now, if you can see the animation (more on that in a sec), what is happening is that I have 3 wide <rect /> tags each with a <linearGradient /> set as there fill. Each rectangle has an <animation /> tag that slowly animates it from left to right and then repeats. I also have 3 <clipPaths /> tags that each contain a <path /> tag whose "d" attribute is a bunch of draw commands I exported from illustrator. This is one of my first times working with SVG graphics and I really enjoyed it. I can't wait until it is more widely supported because it reminds me of Flex and MXML.

That last sentence about it being more widely supported is where I am now. I have a backup image setup as a fallback for users whose browsers don't support SVG, ClipPath, and SMIL animations, but the account managers are a little concerned that the client is going to be upset since we made a big deal about this.

So, today I'm going to revisit one of the ideas of using the canvas to draw this animation. It's a bit more supported right now, but before, I was having trouble getting the vector drawing correct since each part of the logo is an irregular shape. I'm thinking either using EaselJS (since I've used it before) or maybe FabricJS (since I think it might be more popular).

Wednesday, April 16, 2014

Combining PHP template files with associative array models

I've been using Codeigniter for the past 2 years now and I really like it. It might just be the MVC (like) pattern, but it's got a lot of nice built in classes that make building website in PHP a lot quicker, easier and cleaner. So, with my recent exposure to Wordpress, I came to a spot where I was mixing a lot of html with php code, which is something I really hate doing.

Thinking of how, with Codeigniter (and other frameworks), you can combine a *.php template with a data array (or a view model) and render a page I was curious. How does Codeigniter load a php page into a scope with the variables from the supplied data array and spit out the resulting page? After doing a bit of digging I found this nifty function that I ported to my Wordpress theme and now my code looks much cleaner.
function load_template($filename, $data=array()) 
{
    $filename = '/inc/templates/' . $filename . '.php';
    
    if (is_file($filename)) 
    {
        extract($data);
        ob_start();
        
        include( $filename );
        
        $buffer = ob_get_contents();
        @ob_end_clean();
        return $buffer;
    }
    return false;
}
Now with this function you can write a template like...
//inc/templates/biocard.php
<div class="card">
    <div class="photo">
    <?php if( ! empty($image) ) : ?>
        <img src="<?= $image; ?>" alt="<?= $name; ?>" />
    <?php else : ?>
        <img src="/img/missing-user-image.jpg" alt="<?= $name; ?>" />
    <?php endif; ?>
    </div>
    <div class="detail">
        <h4><?= $name; ?></h4>
        <h5><?= $title; ?></h5>
        <?php if( ! empty($email) ) : ?>
            <a class="email" href="mailto:<?= strtolower($email); ?>">Email</a>
        <?php endif; ?>
    </div>
</div>
... and populate it with an associative array:
$model = array(
    'name' => 'Jason',
    'title' => 'Web Developer',
    'email' => 'jason@home.com',
    'image' => 'path/to/profile/image.jpg'
);

return load_template('biocard', $model);