Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you have a tree structure, which a directory is, then you can turn your for() loop into a generator and have it recursively call itself as needed. You'll need two templates (one for files, one for folders), and a view that creates generators for each folder.</p> <p>Here's a file template:</p> <pre><code>&lt;li&gt;{{ file }}&lt;/li&gt; </code></pre> <p>Here's a folder template:</p> <pre><code>&lt;li&gt;{{ file }}&lt;ul&gt;{% for f in subfiles %}{{ f }}{% endfor %}&lt;/ul&gt;&lt;/li&gt; </code></pre> <p>In your main template, you need a starting list for the root folder:</p> <pre><code>&lt;ul&gt;{% for f in subfiles %}{{ f }}{% endfor %}&lt;/ul&gt; </code></pre> <p>And here's the view. This example uses Treebeard, but the logic for branches/leaves is the same as folders/files:</p> <pre><code>from django.template import loader def index(request): def index_maker(): def _index(root): files = os.listdir(root) for mfile in files: t = os.path.join(root, mfile) if os.path.isdir(t): yield loader.render_to_string('demo/p_folder.html', {'file': mfile, 'subfiles': _index(os.path.join(root, t))}) continue yield loader.render_to_string('demo/p_file.html', {'file': mfile}) return _index('/home/httpd/htdocs') c = index_maker() return render_to_response('demo/index.html', {'subfiles': c}) </code></pre> <p>Each node is either a file or a folder. Folders have names, so when rendering a folder we pass that and the list of entries (children) in that folder. The <code>_index()</code> function, by using <code>yield</code>, returns not the list of subfiles but a generator which will produce the results when called by the <code>for</code> loop within the template. This becomes a nifty dance between <code>_index()</code> and the template renderers. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload