'Is there a way to create an HTML table from a list using bottle

I'm using os.listdir to get a list of subdirectories and want to display them as a table on a webpage. I'm using bottle for the web framework. I have seen in the bottle documentation that it can be done by creating an sqlite database from the list and loading it in from there but ideally I'm looking for a way to avoid that intermediate step. I haven't been able to find any documentation without the sqlite step and was wondering if it was possible?

Current code below displays the info I want on the webpage but as a single line of text.

Current Code:
Bottle App

from bottle import Bottle, template, route, run, static_file
import os
import sys

app = Bottle()

dirname = os.path.dirname(sys.argv[0])

@app.route('/static/<filename:re:.*\.css>')
def send_css(filename):
    return static_file(filename, root=dirname+'/static/')


@app.route('/')
def index():
    dir_loc = "/Users/me/Documents"
    dir_data = list(os.listdir(dir_loc))

    return template('index', data = dir_data)


run(app, host='localhost', port=8080, debug=True)

index.tpl

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="static/styling.css">
</head>
<body>
    <div>
        <p>Template for bottle showing {{data}}</p>
    </div>
</body>
</html>


Solution 1:[1]

A SQL database is not needed (unless you want that for persistence). You can generate tables and lists with loops, nicely described in the Bottle doc PDF.

Here's a simple example:

server.py

from bottle import route, run, template
import os

@route("/")
def index():
    dir_loc = "/Users/me/Documents" # replace "me" with your username
    dir_data = list(os.listdir(dir_loc))
    return template("index.tpl", data=dir_data)

if __name__ == "__main__":
    run(host="localhost", port=8080, debug=True, reloader=True)

index.tpl

<!DOCTYPE html>
<html>
<body>
  <table>
    <tbody>
    % for file in data:
      <tr>
        <td>{{file}}</td>
      </tr>
    % end
    </tbody>
  </table>
</body>
</html>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 OneCricketeer