diff --git a/fotogrid.py b/fotogrid.py index 321b4df..9282856 100644 --- a/fotogrid.py +++ b/fotogrid.py @@ -1,22 +1,32 @@ +# SPDX-License-Identifier: GPL-3.0 + + def fotogrid(image_urls): """ Provide a simple responsive fotogrid using flex layout. Depends on the css/fotogrid.css defined styles. + Use jinja {{ fotogrid([....]) }} from templates (registered in app.py) """ - result = '
' - cols = 4 - images = divmod(len(image_urls), cols) - images_per_col = images[0] - if images[1] > 0: - images_per_col += 1 - nbr = 0 - for img in image_urls: - if (nbr % images_per_col) == 0: - if nbr > 0: - result += '
' # closing fotocolumn - result += '
' - result += '' - nbr += 1 + if len(image_urls) == 0: + return "" + + # prepare our 'bins', the columsn of the fotogrid + nbr_of_columns = 4 + prepared_column = [] + for i in range(nbr_of_columns): + prepared_column.append([]) + # sort given image URL into bins + for i in range(len(image_urls)): + prepared_column[i % nbr_of_columns].append(image_urls[i]) + + # form HTML div structure from prepared bins + html = '
' + for column in prepared_column: + if len(column) > 0: + html += '
' + for url in column: + html += '' + html += "
" # closing fotocolumn + html += "
" # closing fotorow - result += "
" # closing fotocolum, fotorow - return result + return html diff --git a/tests/test_fotogrid.py b/tests/test_fotogrid.py new file mode 100644 index 0000000..5a34103 --- /dev/null +++ b/tests/test_fotogrid.py @@ -0,0 +1,38 @@ +# SPDX-License-Identifier: GPL-3.0 +import os + +from fotogrid import fotogrid +from lxml import etree +from io import StringIO + +def check_if_valid_html(html): + parser = etree.HTMLParser(recover=False) + etree.parse(StringIO(html), parser) + assert len(parser.error_log) == 0 + + +def test_fotogrid_empty_list(): + urls = [] + html = fotogrid(urls) + assert len(html) == 0 + + +def check_if_images_result_in(nbr_of_images, rows_expected, cols_expected): + urls = ["dummy.jpg"] * nbr_of_images + html = fotogrid(urls) + check_if_valid_html(html) + assert html.count("fotorow") == rows_expected + assert html.count("fotocol") == cols_expected + assert html.count("