2

I am trying to access the previous and the next blog entries from my current post. Here is what I am doing

{% set params = craft.entries.section('blog').order('postDate asc') %}

    {% set prevEntry = entry.getPrev(params) %}
    {% set nextEntry = entry.getNext(params) %}
    {# to access url, I use #}
    {{ prevEntry.url }}
    {# to access title, I use #}
    {{ prevEntry.title }}

The above works. However, I have an asset under the field handle "featuredImage". I need to access the image URL as well as I need to apply a transform. I am not sure the code below is the most efficient way to do this. Also the image transform is giving me an error (server returns 500 error)

{% for asset in prevEntry.featuredImage %}
    {% do asset.setTransform({ mode:crop, width: 200, height: 200 }) %}
    <a href="{{ prevEntry.url }}"><img alt="{{ prevEntry }}" class="img-responsive center-block" src="{{ asset.url }}">
{% endfor %}

Is looping the best way to access the data considering that there is only one image? Is there a better way? Image transform is also not working (not sure why).

1 Answer 1

2

If you need only one image, you can use the first() function instead of a for loop.

I recommend to check always if a image or entry exists, befor use it. Otherwise you risk to get an error. During development you should turn on the devMode, to see all errors (https://craftcms.com/docs/config-settings).

Here is a code example i would use in your case:

{% if prevEntry %}

    {% set asset = prevEntry.featuredImage.first() %}

    {% if asset|length %}

        {% set thumb = {
            mode: 'crop',
            width: 200,
            height: 200,
            quality: 75,
            position: 'center-center'
        } %}

        <a href="{{ prevEntry.url }}">
            <img src="{{ asset.getUrl(thumb) }}" class="img-responsive center-block"  alt="{{ prevEntry.title }}">
        </a>

    {% else %}
        <a href="{{ prevEntry.url }}">
            <img src="noImg.png" class="img-responsive center-block"  alt="{{ prevEntry.title }}">
        </a>    

    {% endif %}
{% else %}
    <!-- There's no previous entry. -->
{% endif %}
2
  • Nice and complete answer, but why do you use the length filter. The first method returns null if no element is found.
    – carlcs
    Commented Apr 22, 2016 at 6:16
  • 1
    You'v right. You can use {% if asset %} instead of {% if asset|length %} - the result should be the same.
    – Tom Bauer
    Commented Apr 22, 2016 at 6:29

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.