1

I want to query a list of all folders in a specific volume in my front-end template (loggedin users only). I'll need the folderId to display all files of the selected folder.

The idea is to show a list of folders on the left side, right displays a list of files in the selected folder on the left side. The folders need to be the same as in the backend.

{% set assets = craft.assets().volume('handle').folderId(folderId) %}
<ul class="files_folders">
    {% for folder in folders %}
        <li><a href="{{ url('folderId=' ~ folder.id) }}">{{ folder.title }}</a></li>
    {% endfor %}
</ul>
<ul class="files__list">
    {% for asset in assets %}
        <li><a href="{{ craft.digitalDownload.url(asset, options) }}">{{ asset.title }}</a></li>
    {% endfor %}
</ul>

1 Answer 1

2

You can use craft\services\Assets::getAllDescendantFolders to get a list of folders in a given folder. To list all folders in the root folder of the volume, you first need to find the root folder using craft\services\Assets::getRootFolderByVolumeId.

{% set myVolume = craft.app.volumes.getVolumeByHandle('handle') %}
{% set rootFolder = craft.app.assets.getRootFolderByVolumeId(myVolume.id) %}
{% set foldersInRootFolder = craft.app.assets.getAllDescendantFolders(rootFolder) %}

This will return an array of VolumeFolder models that you can iterate through. If you need a hierarchical list, you can access the children with the VolumeFolder::children property, or use craft\services\Assets::getFolderTreeByFolderId to get a hierarchical list. To find all assets in a given folder, use an asset query with the folderId parameter.

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.