October CMS resources and help articles

Simple and to the point. Optimized by the community.

Access images from a media folder in the frontend

5
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

1 comment

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

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