Scaling Cloudinary images using Handlebars templates

556 views
Skip to first unread message

Andrew Iafrate

unread,
Aug 3, 2014, 11:34:32 AM8/3/14
to keyst...@googlegroups.com
I'm trying to display Cloudinary images using different widths and heights in my handlebars template. I'm using the default cloudinaryUrl helper method, and for some reason the width and height values are not getting passed properly. options.width and options.height are undefined, so they always default to 300.

Here's what I put in my template:

<img src="{{cloudinaryUrl data.post.featuredImage width=200 height=200}}" alt="Image"><

I've also tried accessing the underscore methods for resizing within the cloudinaryUrl method:

console.log(context._.scale(200, 200));

But _ ends up being undefined ("Cannot call method 'scale' of undefined" error when I reload the post).

 I'm new to Keystone, so I'm sure there's something I'm missing. Any advice on how I can get different image sizes to show up?

Andrew Iafrate

unread,
Aug 3, 2014, 2:41:15 PM8/3/14
to keyst...@googlegroups.com
Update: I found that the width and height properties I was looking for were actually in options.hash.width and options.hash.height.

JB Folkerts

unread,
Oct 11, 2014, 12:04:58 PM10/11/14
to keyst...@googlegroups.com
I found the following to help quite a lot with using Cloudinary and Handlebars templates.  I installed the cloudinary node.js package with

npm install --save cloudinary

Then I created a replacement helper function that takes all of the cloudinary options (not just height and width).  This works very nicely -- I have a similar helper which calls the cloudinary IMG tag function, but this is more flexible for your hbs template.

Here's my code:

var cloudinary = require('cloudinary'),
        dotenv = require('dotenv');

...

// ### CloudinaryUrl Helper
//
// *Usage example:*
// `{{cloudinaryUrl heroImage width=1200 height=500 crop='fill' gravity='north'}}`
//
// Returns an src-string for a cloudinary image
_helpers.cloudinaryUrl = function(context, options) {
dotenv.load();

// if we dont pass in a context and just kwargs
// then `this` refers to our default scope block and kwargs
// are stored in context.hash
if (!options && context.hasOwnProperty('hash')) {
// strategy is to place context kwargs into options
options = context;
// bind our default inherited scope into context
context = this;
}
// safe guard to ensure context is never null
context = context === null ? undefined : context;
if (context) { 
if (context.public_id) {
var imageName = context.public_id.concat('.',context.format);

// use a regex to strip out the cloudinary username
var cloudinaryRegex = /cloudinary\:\/\/([0-9]+)\:(.+)\@(.+)/;

var cloudConfigHash = process.env.CLOUDINARY_URL.match(cloudinaryRegex);

return cloudinary.url(imageName, options.hash);
}
}
};


Reply all
Reply to author
Forward
0 new messages