Dev Notes

Software Development Resources by David Egan.

Using Masonry With WordPress and Sage 8



David Egan

Masonry is a very popular open-source grid layout library by David DeSandro. It provides a great way of laying out client images, especially when the sizes and aspect ratios are all over the place.

You can use Masonry as a jQuery plugin, or initialize it with vanilla JavaScript - though I haven’t tried the latter.

Installing Masonry when you’re using the Sage starter theme is probably best done with Bower. There are a few important issues that you need to be aware of.

Most importantly, you need to reference the masonry.pkgd.js file (rather than masonry.js) from the Masonry bower package for the script to run properly.

Install Masonry with Bower

In the project root, build Masonry with Bower:

bower install masonry --save

You may also need the imagesloaded plugin:

bower install imagesloaded --save

Conditionally Load Masonry

Masonry is generally only required on some pages, so we need to prevent masonry being auto-built into main.js - to do this, we need to amend assets/manifest.json:

manifest.json

{
  "dependencies": {
    "main.js": {
      "files": [
        "scripts/main.js",
        "scripts/sticky-navbar.js"
      ],
      "main": true,
      "exclude": {
        "bower": [
          "outlayer",
          "fizzy-ui-utils",
          "get-size",
          "ev-emitter",
          "masonry",
          "imagesloaded"
        ]
      }
    },
    ...
    "masonry.js": {
      "bower": [
        "masonry",
        "imagesloaded"
      ],
      "files": [
        "scripts/masonry-control.js"
      ]
    }
...

…now the bower packages for masonry & imagesloaded, along with the masonry-control.js script will be concatenated into dist/masonry.js. This file can then be enqueued where it is needed.

Masonry Dependencies

Masonry needs the masonry.pkgd.js file to pull in necessary dependencies. Don’t try to do this manually - it will result in a mess.

Instead set up an override in the project bower.json:

bower.json

{
  ...
  "overrides": {
    "bootstrap-sass": {
      "main": [
        ...
      ]
    },
    "font-awesome": {
      "main": [
        "./scss/font-awesome.scss",
        "./fonts/\*"
      ]
    },
    "masonry": {
      "main": ["./dist/masonry.pkgd.js"],
      "dependencies": {}
    }
  }
}

The Future: Sage 9

This article probably has a short shelf-life - Sage 9 is coming up, and this will drop Bower entirely - project dependencies will be managed by Webpack/NPM.


comments powered by Disqus