croxton / imgixer

Generate Imgix URLs in Craft 3
MIT License
11 stars 4 forks source link

[Question] Usage with Element API #1

Closed umkasanki closed 3 years ago

umkasanki commented 3 years ago

Hey. Could you please show an example of how to use your plugin with the Element API plugin? Thanks

croxton commented 3 years ago

Not forgotten this, just been super busy. I'll try to find time to add an example next week.

croxton commented 3 years ago

Sorry for delay! Here's an example of using Imgixer with the Element API, assuming your image field is named 'image'. Basically, pass the image path as the first argument to the function, and an array of Imgix parameters as the second argument.

<?php

use craft\elements\Entry;
use craft\helpers\UrlHelper;
use croxton\imgixer\twigextensions\ImgixerTwigExtension;

return [
    'endpoints' => [
        'news.json' => function() {
            return [
                'elementType' => Entry::class,
                'criteria' => ['section' => 'news'],
                'transformer' => function(Entry $entry) {
                    $asset = $entry->image->one();
                    return [
                        'title' => $entry->title,
                        'url' => $entry->url,
                        'jsonUrl' => UrlHelper::url("news/{$entry->id}.json"),
                        'summary' => $entry->summary,
                        'image'   => (new ImgixerTwigExtension)->imgix($asset->path, array(
                            'ar' => '16:9',
                            'w' => 2000,
                            'signed' => true
                        ))
                    ];
                },
            ];
        }
    ]
];
umkasanki commented 3 years ago

Thanks!