Coverage for website/templatetags/get_type.py: 77%
30 statements
« prev ^ index » next coverage.py v7.5.0, created at 2025-09-13 15:29 -0300
« prev ^ index » next coverage.py v7.5.0, created at 2025-09-13 15:29 -0300
1"""Template tag helpers for discovering available "tile" templates.
3This module provides a `get_tile_types` simple tag that returns a list of
4tile template names found under `website/templates/tiles/` (files named
5like `tile_*.html`). It falls back to scanning any template directories
6configured in settings.TEMPLATES[*]['DIRS'] if the package-local folder is
7not present.
9Usage in template:
11 {% load get_type %}
12 {% get_tile_types as tile_types %}
13 {% for t in tile_types %}
14 {{ t }}
15 {% endfor %}
17The tag returns the template filename stem (without .html), e.g. 'tile_small'.
18"""
20from pathlib import Path
22from django import template
23from django.conf import settings
25import website as website_pkg
27register = template.Library()
30@register.simple_tag
31def get_tile_types():
32 """Return a list of available tile template names (stem without .html).
34 It first tries to read files from the package's `templates/tiles/`
35 directory (useful for this project layout). If none are found, it
36 falls back to scanning template dirs listed in settings.TEMPLATES.
37 """
38 types = []
40 # Primary: project app's templates/tiles folder
41 try:
42 base = Path(website_pkg.__file__).resolve().parent / "templates" / "tiles"
43 if base.exists() and base.is_dir():
44 for f in sorted(base.iterdir()):
45 if f.is_file() and f.suffix == ".html" and f.name.startswith("tile_"):
46 types.append(f.stem)
47 except Exception:
48 # best-effort; ignore errors and try fallback
49 types = []
51 # Fallback: scan configured template DIRS
52 if not types:
53 tmpl_dirs = []
54 for cfg in getattr(settings, "TEMPLATES", []):
55 tmpl_dirs.extend(cfg.get("DIRS", []))
57 for d in tmpl_dirs:
58 try:
59 p = Path(d) / "tiles"
60 if p.exists() and p.is_dir():
61 for f in sorted(p.iterdir()):
62 if (
63 f.is_file()
64 and f.suffix == ".html"
65 and f.name.startswith("tile_")
66 ):
67 types.append(f.stem)
68 except Exception:
69 continue
71 return types