4

I want my site to serve 1X and 2X images depending on the browser using something like Picturefill, and I don’t want the 1X version to just be automatically generated using a transform - I want to be able to upload separate 1X and 2X versions, and have them be linked together. How can I go about that?

Brandon Kelly
  • 34,307
  • 2
  • 71
  • 137

1 Answers1

7

You can do that like so:

  1. Create a new Assets field called “Hi-Res Image” (handle “hiResImage”) with the following settings:

    • Restrict uploads to a single folder: [ √ ]
    • Upload Location:
      • [same source you’re uploading 1X images to]
      • {folder.path}_2x/
    • Restrict allowed file types:
      • [ √ ]
      • [Images]
    • Target Locale: [Same as source]
    • Limit: 1
  2. Go to Settings > Assets > [your source] > Fields tab, and add your new Hi-Res Image field to the layout.

With that set up, after you select 1X images in your main Assets field, you will be able to double-click on them and see your “Hi-Res Image” Assets field in their metadata modals. You can drag your 2X image into that, and it will automatically get saved into a _2x/ subfolder wherever its parent image lives.

From your templates, you can then output <img> tags that point to both images:

{% for image in entry.myAssetsField %}
    {% set hiResImage = image.hiResImage.first() %}

    <img srcset="{{ image.url }}
        {%- if hiResImage %}, {{ hiResImage.url }} 2x{% endif %}">
{% endfor %}
Brandon Kelly
  • 34,307
  • 2
  • 71
  • 137