1

Is it possible to list subfolders from a specific folder?

Context: I'm printing out hundreds of icons which are maintained by moving a directory structure directly over to my public assets folder. Currently, I grab and list all icons by looking at the parent folder for icons:

{% for image in craft.assets.source('iconLibrary').limit(null) %}
   <li>...</li>
{% endfor %}

I'd like to call and list them by their individual folder names though. Is there a way to take a specific folder and return a list of subfolders?

Update: Brad's solution works! Though it's somewhat awkward having to call an image first to start at AssetFileModel. Hopefully this can be optimized as I'm running through a loop like the one above for each child folder now—

<!--find image in parent icon folder to access folder via AssetFileModel.-->
{% for image in craft.assets.id('9328') %} 
   <!-- get children of that asset's folder -->
   {% for subfolder in image.folder.getChildren() %} //
      {{ subfolder }}   //prints each child folder name
   {% endfor %}
{% endfor %}
1

Not a complete answer, but in your example image if going to be an instance of AssetFileModel.

AssetFileModel has a getFolder method that returns an instance of AssetFolderModel.

AssetFolderModel has a getChildren method you could loop through to get all of the subfolders for the given folder.

Depending on how numerous your file/folder structure is, though, it might be more efficient to do this from PHP in a custom plugin rather than to do it from Twig.

|improve this answer|||||
  • Thanks, this gets it done. Is there a way to call a folder and get the children directly without starting from an image? I'm currently putting a tiny image that never gets displayed in the target folder for now in order to make that call. – Ryan Jun 30 '17 at 5:37
  • craft.assets.folderId(1).find() will give an array of AssetFileModels for every image in that folder. – Brad Bell Jun 30 '17 at 21:40

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.