Showing posts with label module. Show all posts
Showing posts with label module. Show all posts

Wordpress, Timber & Twitter Bootstrap

Wordpress is one of the most popular CMS blogging platforms on the internet today, with the latest updates it's really improved in terms of user experience for the admin user. However there is still one massive pain for developers in the template system....where there isn't really one!

Internationalisation & Localisation in AngularJS

Set up AngularJS projects to be translated using html template tags. This post looks at how you can use the Angular libraries plus a custom filter to ensure content is contextualised to the user.

The ultimate layout engine for backend and frontend

I have created a lot of sites over the years and the single biggest problem I have, an always face is the layout engine. The layout engine is the way a view is mapped with data and outputted onto the page.

Backend libraries and frameworks have a tough choice of choosing between:
- fixed templates, predefined and hardcoded, less flexible
- loose templates, built using reusable blocks, look messy and unexpected results

Frameworks such as Drupal and Wordpress go for the flexible solution. However users end up overriding them using fixed templates because of the way they are structured. They also suffer from being far too complicated to edit and update and confusing users into putting the files in the wrong places.

So how can we solve this? We need a solution that sits firmly in the middle of fixed and flexible. The key is to determine which elements should be fixed and which should be flexible.

The solution is to have a flexible layout grid (rows and columns) with fixed module templates (item html). This works well because you retain control of both but in separate places. This is the basis behind the ultimate layout engine which I've developed.

backend code
- list of pages with urls (if the url is all then it will be shown on all pages)
- list of view templates that appear on each page
- each view specifies where it appears on the page using a row and col number
- each view also species which model (data) table and corresponding model (data) row should be mapped to it

The layout table

url view row col model modelrow
all Head 1
1
all Logo 1 1 1 0
all Contact 1 2 1 0
all Navigation 2 2 1

Banner 3 2 2 1

TextSmall 4 2 2 1

Highlights 4 2 1
events BannerText 3 1 3 0
events Highlights 3 2 1
all Foot 1
1

the logic of this table:
- loop through each item
- if item url equals the current page url, or the item url equals 'all' then render the view using the model table and model row
- then add each render view into an array of rows and cols for the page
- If no row or col values exists then don't put them inside a row and col, put them as their own item in the array.

Here is an example of the view rendered with model data, then put into an array in the correct order based upon it's row and col numbers:

The layout array

var data = [
    {
        'type': 'Head'
        'data': '<div class="head">head html</div>'
    },
    {
        'type': 'row'
        'data': [
            {
                'type': 'col',
                'data': '<div class="banner">banner 1 html</div>'
            }
        ]
    },
    {
        'type': 'row'
        'data': [
            {
                'type': 'col',
                'data': '<div class="text">text 1 html</div>'
            },
            {
                'type': 'col',
                'data': '<div class="text">text 2 html</div>'
            },
            {
                'type': 'col',
                'data': '<div class="text">text 3 html</div>'
            }
        ]
    }
]

the logic for this next step is to:
- loop through each item in the layout array
- if the type is not row or col then output the data html
- if the type is a row then create a row html
- if the type is a col then create col html
- add the inner html inside the col and output to the page

And this is how our html will look after all of this:

<div class="head">head html</div>
<div class="row">
    <div class="col">
        <div class="banner">banner 1 html</div>
    </div>
</div>
<div class="row">
    <div class="col">
        <div class="text">text 1 html</div>
    </div>
    <div class="col">
        <div class="text">text 2 html</div>
    </div>
    <div class="col">
        <div class="text">text 3 html</div>
    </div>
</div>

If you want more control over the layout then you can add some more columns to the layout table which contain classes for each row and col.

The layout table with row and col classes

url view row col model modelrow rowclasses colclasses
all Head 1
1
row980
all Logo 1 1 1 0 row980
all Contact 1 2 1 0 fill1of3
all Navigation 2 2 1
row980

Banner 3 2 2 1 row980

TextSmall 4 2 2 1 row980

Highlights 4 2 1
fill1of3
events BannerText 3 1 3 0 row980
events Highlights 3 2 1
all Foot 1
1
row980

Very simple logic, which makes your views much easier to maintain as they don't contain layout containers:

<div class="text">{{ item.name }}</div>

Hope that helps you!

Sharing Server side and Client side templates

Often when creating a module or gadget you will want to render something server-side, then as the module loads with JavaScript, update the html with the new data/logic.

This presents a few questions:

- will the data load once, or refresh?
- is the data already embedded in the page?
- could the data take time to load?
- will we know that before creating our module?

- if data is coming from a javascript ajax request, will the html be empty until it loads?
- should we show a loader icon while this is happening?
- what if the server wants to render the module with some data and not load a feed?
- do we need a server-side template and then a javascript template

So many questions that prevent us from completing our module, and potentially could also force us to make changes to it later down the line as the functionality changes. I've come across this problem many times and come to a great solution.

Sharing server-side and client-side templates
Your html template should be the same for both server-side and client-side which means you need to pick the same library for both or implement the same custom template code. For this example i'm going to be using:

- Jinja for python,
- Twig for php
- Twig.js for JavaScript

A normal html file with div for javascript to attach to, javascript template and data would look something like this:

Main.html

<div id="list1" class="list"></div>


<script id="tmpl" type="text/template">
    <ul>
        {% for item in items %}
            <li><a href="{{ item.url }}">{{ item.name }}</a></li>
        {% endfor %}
    </ul>
</script>

<script>
    var list1 = new List('list1', [{'name': 'Item 1', 'url': 'http://www.google.co.uk'}]);
</script>


This is bad because html is combined with javascript script tags. The key is to separate the two cleanly.

Main.html
<div id="list1" class="list">
    {% include 'html/modules/Item.html' %}
</div>
<script id="tmpl" type="text/template">
    {% include 'html/modules/Item.html' %}
</script>


<script>
    var list1 = new List('list1', [{'name': 'Item 1', 'url': 'http://www.google.co.uk'}]);
</script>



List.html

  <ul>
  {% for item in items %}
    <li><a href="{{ item.url }}">{{ item.name }}</a></li>
  {% endfor %}
  </ul>

Now you can keep three files for each module which makes developing really easy:
List.html
List.css
List.js

Automated modules
Patterns start to emerge from writing our code this way, which allows us to automate processes. Lets output the modules dynamically:

Main.html

{%
    set modules = [
        { 'name': 'List', 'id': 'list1', 'data': [{'name': 'Item 1', 'url': 'http://www.google.co.uk'}] },
        { 'name': 'List', 'id': 'list2', 'data': [{'name': 'List 1', 'url': 'http://www.google.com'}] }
    ]
%}

{% for item in modules -%}

    <div id="{{ item.id }}" class="list">
        {% include 'html/modules/'~item.name~'.html' %}
    </div>
    <script id="tmpl" type="text/template">
        {% include 'html/modules/'~item.name~'.html' %}
    </script>


    <script>
        var {{ item.id }} = new {{ item.name }}('{{ item.id }}', {{ item.data }});
    </script>
{% endfor -%}

By outputting automatically you can keep all of your modules consistent while developing and ensure the all conform to the same structure.

An added benefit is that your backend developer can use you object to create the model for the CMS. He has all of the fields that the view requires to be rendered.

Saves a world of pain too when the data needs to be updated via ajax instead of server side.




Defining and Extending JavaScript Modules

After writing a few modules you will find yourself reusing the same parts of code such as:

- initiating a function with a prototype
- getting a reference to the dom element
- merging options with defaults

These are duplicated in each Module Class you write. here is a simple example of code duplication:

Panel.js
function Panel(id, options) {
this.el = document.getElementById(id);
if (!this.options) { this.options = {}; }
for (var item in options) { this.options[item] = options[item]; }
this.init();
}

Panel.prototype = {

init: function() {
this.el.innerHTML = 'options: <pre>'+JSON.stringify(this.options)+'</pre>';
}
}

Item.js
function Item(id, options) {
this.el = document.getElementById(id);
if (!this.options) { this.options = {}; }
for (var item in options) { this.options[item] = options[item]; }
this.init();
}

Item.prototype = {

init: function() {
this.el.innerHTML = 'A new item!';
}
}

Obviously we can improve on these 25 lines of code as these modules share the same init code. So here's a way to improve it using define as a global function name:

Main.js
function define(name, module, unique) {
function Module(id, options) {
this.el = Utils.getEl(id);
if (!this.options) { this.options = {}; }
for (var item in options) { this.options[item] = options[item]; }
this.init();
}
Module.prototype = module;
if (!window[name]) { window[name] = Module; }
}

Panel.js
define('Panel', {
init: function() {
this.el.innerHTML = 'options: <pre>'+JSON.stringify(this.options)+'</pre>';
}
});

Item.js
define('Item', {
init: function() {
this.el.innerHTML = 'A new item!';
}
});

Now it is 22 lines of code and we will save many more for every new module created. The added benefit of this is that we can now update the module base in one place for all modules at once. Here is an example where i've added the ability to define a singleton module that will only exist once ever on a page:

Main.js
function define(name, module, unique) {
if (unique == true) {
if (!window[name]) { window[name] = module; }
}
else {
function Module(id, options) {
this.el = Utils.getEl(id);
if (!this.options) { this.options = {}; }
for (var item in options) { this.options[item] = options[item]; }
this.init();
}
Module.prototype = module;
if (!window[name]) { window[name] = Module; }
}
}

Utils.js
define('Utils', {
elements: {},
getEl: function(id) {
if (this.elements[id]) {
return this.elements[id];
}
else {
this.elements[id] = document.getElementById(id);
return this.elements[id];
}
}
}, true);

So Utils is now defined as a singleton instead of a function with a prototype. But what if we need to extend modules off each other? Well this becomes simpler now as we can save and merge modules within our define function.


var modules = {};

Main.js
modules[name] = module;
if (module.extend) {
module.superclass = modules[module.extend];
module = Utils.extend(Utils.clone(module.superclass), module);
}


First we are saving all module prototypes to a list we can reference by their name. Then if a module contains an extend property we will merge the two modules together and set a property called superclass to reference the parent module at any later date.

The Utils class then is updated with the additional clone and extend functions:

Utils.js

define('Utils', {
elements: {},
getEl: function(id) {
if (this.elements[id]) {
return this.elements[id];
}
else {
this.elements[id] = document.getElementById(id);
return this.elements[id];
}
},
clone: function(o) {
var a = {};
for (var i in o) {
if (o.hasOwnProperty(i)) { a[i] = o[i]; }
}
return a;
},
extend: function(o, o2) {
for (var p in o2) {
try {
if (o2[p].constructor == Object) { o[p] = this.extend(o[p], o2[p]); }
else { o[p] = o2[p]; }
}
catch (e) { o[p] = o2[p]; }
}
return o;
}
}, true);


If you would like to see a real-world example of these modules in action, you can look at the source of my portfolio:
http://kimturley.co.uk/debug.html

http://kimturley.co.uk/js/Main.js
http://kimturley.co.uk/js/modules/Utils.js
http://kimturley.co.uk/js/modules/Events.js
http://kimturley.co.uk/js/modules/Template.js
http://kimturley.co.uk/js/modules/List.js




Writing efficient JavaScript modules


Writing modular JavaScript gives you many advantages:
- reusable code
- separation of layout and logic
- prevent code duplication
- cleaner and easier to read

However there are still a few common mistakes which can be made, even when following guides. I've listed some of those below.

1) Putting your JavaScript code at the bottom of the html page prevents JavaScript from blocking the  browser rendering.

<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Module Example</title>
</head>
<body>
<div id="example"></div>
<script src="js/modules/Module.js"></script>
</body>
</html>

2) When writing a JavaScript Class The function should only hold the unique properties of the module. Things like the html dom element and it's options. These are duplicated for each instance of the module so 1000 modules means 1000 references to elements and 1000 sets of options.


function Module(id, options) {
this.el = this.getEl(id);
this.options = options;
this.init();
}

3) The prototype should only hold the shared properties of the module. This is important as by adding it to the prototype, the object is only ever stored once in browser memory, even if you create 1000 instances of the module!


Module.prototype = {
name: 'Module',
elements: {},
init: function() {
this.el.innerHTML = 'options: <pre>'+JSON.stringify(this.options)+'</pre>';
},
getEl: function(id) {
if (this.elements[id]) {
return this.elements[id];
}
else {
this.elements[id] = document.getElementById(id);
return this.elements[id];
}
}
}

4) Now you can create instances of your module which will be very efficient and quick. In this example I have also added a caching function to the elements to ensure each element is only located and referenced once!


var module = new Module('example', {
test: 'hello world',
param: 23476
});




Writing jQuery plugins

There are a few simple rules to writing jQuery plugins which prevent issues later down the line.

1) start with an IIFE which passes through jQuery into its scope

(function($, window, undefined) {
// your plugin will go here 
}(jQuery, window));

2) Define your plugin functions as an object inside those brackets

var module = {
name: 'Carousel',
  defaults: {
    propertyName: 'value'
  },
init: function() {
// put your init code here
},
update: function() {}
}

3) Then register your module object as a function prototype so we can have multiple instances

function Plugin(element, options) {
    this.el = element;
    this.options = $.extend({}, module.defaults, options);
    this.init();
}
Plugin.prototype = module;

4) Then register as a jquery plugin with some code to test whether it has already been init'd on that element before

$.fn[module.name] = function(options) {
    var args = arguments;
    if (options === undefined || typeof options === 'object') {
        return this.each(function() {
            if (!$.data(this, 'plugin_' + module.name)) {
                $.data(this, 'plugin_' + module.name, new Plugin(this, options));
            }
        });
    } else if (typeof options === 'string' && options[0] !== '_' && options !== 'init') {
        return this.each(function() {
            var instance = $.data(this, 'plugin_' + module.name);
            if (instance instanceof Plugin && typeof instance[options] === 'function') {
                instance[options].apply(instance, Array.prototype.slice.call(args, 1));
            }
        });
    }
}

5) Then call your plugin on elements to load it

$('#example').Carousel({optionparam: 'example'});

6) To call another function you can use the format:

$('#example').Carousel('update', {newparam2: 'another example'});

Google mod pagespeed

If you are looking to increase the speed and performance of your website, Google have just release an Apache server module which improves page loading times by changing the way resources are delivered.

I haven't given it a try yet but people are reporting pages loading at almost twice the speed! That will make a big difference to your audience and definitely worth installing:
https://developers.google.com/speed/pagespeed/mod