3

I'm using asset transforms in various places to serve appropriately sized images via a Twig macro that I feed an entry and the name of a transform into (the idea is to have the same bit of HTML, but with differently sized images depending on the context). The way I get the image URL is as follows:

entry.mainImage.first().getUrl(transform)

However, at the moment if the named transform is not found (ie. if the value of transform doesn't correspond to the name of an existing transform) I get a Craft error. For my purposes a better failure mode would be to just serve the untransformed, full-size image. I'm wondering if there's a way of checking whether a named transform exists? That way I could just set transform to null if it's not found and it should fail gracefully.

4
  • Are there other possibilities that would make your macro break besides "if the value of transform doesn't correspond to the name of an existing transform"?
    – carlcs
    Commented Aug 11, 2014 at 17:21
  • No, not that I know of. The reason I'm asking is that the macro is being used across lots of templates and I've tweaked the functionality slightly, which means that in some places the macro receives an argument that doesn't correspond to an existing transform. This breaks all my templates, and it would be nice to catch that possibility in the macro so that if there's still a template or partial somewhere that I've missed that's calling the macro in the old way, I can be sure it won't break the page.
    – Nick F
    Commented Aug 11, 2014 at 17:29
  • What about using cmd+shift+f in Sublime Text to search in all your template files for that old macro syntax? Work with regex too!
    – carlcs
    Commented Aug 11, 2014 at 17:43
  • Ha, thanks. I actually already did that, as it happens. But if someone, say, deletes or renames an asset transform, the site will still break. I'd ideally like to be able to write my templates to protect against that in principle.
    – Nick F
    Commented Aug 11, 2014 at 18:13

1 Answer 1

4

You can check for the existence of a transform within your controller (for example), as follows:

 if (craft()->assetTransforms->getTransformByHandle('jimbob')) {
      // Transform exists.
 } else {
      // Transform does not exist (null is returned).
 }

Unfortunately, there doesn't seem to be an equivalent service (such as craft.assetTransforms) for use within templates.

Stephen

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.