Turning folders into web pages with Python: Difference between revisions

From XPUB & Lens-Based wiki
No edit summary
Line 63: Line 63:


  $ uv run main.py
  $ uv run main.py
==8. See the result==
Open the <code>index.html</code> file in your browser.

Revision as of 17:38, 2 February 2026

For the prototyping class on 10 February 2026 in the context of SI29.

1. Install uv

(if you don't have uv already)

https://docs.astral.sh/uv/getting-started/installation/

$ curl -LsSf https://astral.sh/uv/install.sh | sh

2. Initialize project

$ uv init gallery

3. Prepare an assets folder

$ mkdir assets

4. Put some files in the assets folder

Just copy and paste!

5. Work on main.py

from glob import glob
from jinja2 import Template

def main():
    assets = glob('assets/*')

    with open('template.html','r') as f:
        html_template = f.read()

    jinja_template = Template(html_template)
    output = jinja_template.render(assets=assets)

    with open('index.html', 'w') as f:
        f.write(output)

if __name__ == "__main__":
    main()

6. Work on your template.html

<style>
img {
	max-width: 200px;
	object-fit: contain;
}
</style>

<ol>
{% for asset in assets %} 
<li><img src="{{asset}}"/></li>
{% endfor %}
</ol>

7. Run the script

$ uv run main.py

8. See the result

Open the index.html file in your browser.