2

I'm new in Craft CMS and i want to know if it's posssible to loop every file which is in a subfolder in the Backend media folder? For Example: Show me all files in Backend/craft/web/media/images/database.

for example

    {% for files in ""directory to folder"".database.all() %}
    <div class="database">
        <div class="database__wrapper">
            <div class="databsae__file">
                {% set file = file.databaseImage.one() %}
                <img class="database__image" src="{{ file.url() }}" alt="{{file.title }}">
            </div>
        </div>
    </div>
    {% endfor %}

Thx

1
1

You can query for assets by using the craft.assets() query factory, see the documentation on Querying Assets for details.

There are a couple of ways to narrow down a query. If the folder you mentioned is it's own volume, you can query by volume to get all files in that volume. To narrow it down to a single folder in the volume, you need to know the folder ID. You can get the folder ID using the assets service.

<?php

use craft\elements\Asset;

$volumeService = Craft::$app->getVolumes();
$assetService = Craft::$app->getAssets();

// replace with the handle of the volume your folder is in
$imageVolume = $volumeService->getVolumeByHandle('images');

// replace with the path of the folder you want to query for assets in, relative to the volume root
$imageStorageDir = 'user/uploads';

$imageFolderId = $assetService->ensureFolderByFullPathAndVolume($imageStorageDir, $imageVolume);

$assetsInFolder = Asset::find()->folderId($imageFolderId)->includeSubfolders()->all();

Leave out includeSubfolders if you don't want to include subfolders, obviously.

Here's the same thing slightly condensed in Twig:

{% set imageVolume = craft.app.getVolumes().getVolumeByHandle('images') %}
{% set imageStorageDir = 'user/uploads' %}
{% set imageFolderId = craft.app.getAssets().ensureFolderByFullPathAndVolume(imageVolume, imageStorageDir) %}

{% set assetsInFolder = craft.assets()
    .folderId(imageFolderId)
    .includeSubfolders()
    .all()
%}

Keep in mind that in order to be found by asset queries, each asset must exist in the database. This is the case if you're uploading assets through the backend or adding them programmatically – but not if you're just uploading a media folder to the server.

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.