October CMS resources and help articles

Simple and to the point. Optimized by the community.

Access images from a media folder in the frontend

11
by mjauvin, last modified on August 11th, 2019

Method1: Use the storage_path helper and the File::files method to list the images in a path.

==
function onInit()
{
   $dir = storage_path('app/media/your-folder');
   $this['files'] = File::files($dir);
}
==
<ul>
    {% for file in files %}
       <li>{{ file }}</li>
    {% endfor %}
</ul>

Method2: Use the Storage::files method to list the images in a path.

==
function onInit()
{
   $dir = 'media/your-folder';
   $this['files'] = Storage::files($dir);
}
==
<ul>
    {% for file in files %}
       <li>{{ file }}</li>
    {% endfor %}
</ul>

Note: Method1 returns an array of Symfony\Component\Finder\SplFileInfo objects which give much more information about the files (size, perms, owner, etc).

Discussion

3 comments

0
alxy
Post on April 5th, 2019 7:31 AM

There is also a covenient method directly in the MediaLibrary: https://github.com/octobercms/october/blob/develop/modules/system/classes/MediaLibrary.php#L114

0
DennisF
Post on March 6th, 2021 4:00 PM

This does not seem to work for me. I get an error for both methods:

Parse error: syntax error, unexpected '$dir' (T_VARIABLE), expecting ';' or '{'

Really like October CMS and would love some help?

0
DennisF
Post on March 6th, 2021 4:09 PM

Nevermind, just me being stupid was missing a "{" after the onInit

function onInit() { $dir = 'media/stories/aisling/'; $this['files'] = Storage::files($dir); }

We use cookies to measure the performance of this website. Do you want to accept these cookies?