8

This seems like it should be really simple. I set the field for an image asset, linked it to the entry type I want it associated to, and then uploaded the image in the cms to the folder I specified.

So now, when I call {{ entry.featureImage }} it should return the object of that image. I want its URL, because I want to place it in a special image tag. <img class="img-responsive" src="{{ entry.featureImage }}"> Now I know this returns an error that says "Object could not be converted to string". Because I need to modify it to get the string of the URL. How can I do this? I feel like I've tried everything and scoured the docs and internet. I cant just attach a .getURL() or .url like would make a whole ton of sense. I've even set entry.featureImage as a variable and then called image.url on it. Or .getImg('featureImage') maybe? But it needs the class of img-responsive.

This needs to be possible so that the CMS can allow for images to be specified and uploaded for specific spots in the website.

15

I bet this trips up a lot of people at first, but your asset field will return a ElementCriteriaModel, not your image.

To get to image, you need to fetch it. If your field has only one image, you will do something like this:

{# Fetches the first image #}
{% set image = entry.featureImage.first() %}
{# It's good to check if you actually have an image before trying to get the url #}
{% if image %}
    {{ image.url }}
    {# Or alternatively #}
    {{ image.getUrl() }}
    {# If you want to get a specific transform: #}
    {{ image.getUrl('transformHandle') }}
{% endif %}

The Assets fields documentation got some good examples on the different use cases.

  • Thank you! I was missing .first(). Although I don't understand why I need to specify to get the first in the array, when the single image is the only one uploaded, it works with that added. Good tip with the checking if it exists too. – Ryan Maskell Sep 30 '14 at 21:02
  • As Fred said, it can be confusing... It's important to specify the first because technically your assets field can hold more than one asset. Even if you've only uploaded a single asset (or even set the "maximum" allowed assets to 1), your assets field will still hold its data in an array-like format. – Lindsey D Sep 30 '14 at 21:34
  • 2
    I've found it helpful to make sure all my relation field handles are plural, even if I only intend on there being one element. It's a lot easier to remember to add the .first if you've already got {{ entry.featureImages }}. – Mike Pepper Sep 30 '14 at 22:33

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.