I am migrating a static HTML site to Craft, and trying to apply image transforms to specific images without running them through a Craft field.

In other words, I have the image path hardcoded in the template, and would like to apply an existing transform to it.

I have tried to set my image path as a Twig variable and then call getUrl('medium') on that - but i get the error because I am passing a String value.

I also tried to store the image path in an array variable, but it's not working either.

Is there anyway to achieve this and pass a static path to getUrl()?


I don't think that Craft can do this natively, and would guess that it needs an AssetModel in order to determine where to create the image transforms, etc. Your best bet would be to add the images to Craft.

Assuming the images are stored locally, this is pretty easy:

  • create an asset source that points to the folder where your images are stored
  • go to settings and update asset indexes for the new asset source

If your filenames are all unique then you can reference the image by filename in your template:

{% set asset = craft.assets.filename('filename.jpg').first() %}
{% if asset is defined %}
    <img src="{{ asset.getUrl('medium') }}">
{% endif %}

Otherwise, you will need to add folderId to the criteria, or add the asset to the current entry via an assetField and reference through the assetField.

(Another option, although not recommended, would be to add the images to an asset source as above; update indexes; then create a template that just renders all images in the asset source (using source('assetSource') criteria), rendered with the given transform. You can then just hard code the path to the image using the image transform folder ('myimages/_medium' folder). But you could just as easily use photoshop for this.)

  • It's good to have you back around, Douglas. :)
    – Brad Bell
    Mar 23 '16 at 4:26
  • This solution works wonderfully! I forgot to mention that the image was already in the Craft assets index - so adding the craft.assets.filename() variable did the trick perfectly. Thanks a ton!
    – simonswiss
    Mar 23 '16 at 4:34
  • Great! Glad it worked. Just watch out for unique filenames or you may inadvertently render the wrong image :) Mar 23 '16 at 4:39
  • Nice answer, it is exactly what I was searching for. Thanks!
    – Masiorama
    Sep 20 '16 at 9:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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