I'm currently using a route to get a specific asset for a gallery section of my site. URL is similiar to http://craft.dev/place/place-name/gallery/1 (Where 1 is the number in the gallery.)

I'm currently doing the following in the template

{% extends '_layout' %}

{% set entry = craft.entries.slug(craft.request.getSegment(2)).first() %}

{% set image = entry.images[craft.request.getSegment(4) - 1] %}

{% block content %}


{% endblock %}

It works currently but is there a cleaner way to do it without the - 1?


That’s definitely the way to do it!

I would set the URL segments to their own variables, to clean it up a little bit.

{% set entrySlug = craft.request.getSegment(2) %}
{% set imageOffset = craft.request.getSegment(4) - 1 %}

Also, probably a good idea to include the section param when fetching the entry, in case you have another entry in another section with the same slug.

{% set entry = craft.entries.section('mySection').slug(entrySlug).first() %}

The only issue I can think of is, if the 4th segment is greater than the total number of assets, you’re going to get an error. You can grab the asset using the offset param instead, and check to see if anything is returned:

{% set image = entry.images.offset(imageOffset).first() %}

{% if not image %}
    {% exit 404 %}
{% endif %}
  • Brandon, is it save to omit the brackets in first() and in all other empty parameters?
    – carlcs
    Jun 14 '14 at 21:24
  • @ChristianSeelbach Sure. There’s a slight performance improvement if you include them, because Twig knows for sure that it’s a method, so it doesn’t have to figure that out for itself every time, but it’s a micro-optimization at best. Jun 14 '14 at 21:26
  • Cool! yeah I added in that section param shortly after. Is there any possibility of adding what I've done into a method for future users. Not sure how often the use case would be necessary but having a clean(er) way to call a particular asset from a field, like file.nth(n) would be quite useful! Jun 14 '14 at 21:30
  • @SeanO'Grady I like that nth() idea. Adding to the list :) Jun 14 '14 at 21:31
  • @SeanO'Grady That nth() function made it into Craft 2.2 ;) Sep 2 '14 at 19:46

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.