From 2509c8f48b998be6c36dd714d6bb9deb9740678a Mon Sep 17 00:00:00 2001 From: Matthias Mair Date: Mon, 27 Nov 2023 12:13:06 +0100 Subject: [PATCH] [PUI] Template helpers (#5993) * added helper to render an instance for an url * made manifest loading more error tolerant (to the user) * refactored return string composition * made manifest path configurable * made django app relative * fix typing for py 3.9 * move css up --- InvenTree/web/templatetags/spa_helper.py | 35 +++++++++++++++++------- 1 file changed, 25 insertions(+), 10 deletions(-) diff --git a/InvenTree/web/templatetags/spa_helper.py b/InvenTree/web/templatetags/spa_helper.py index edea064d89..5da2a0add9 100644 --- a/InvenTree/web/templatetags/spa_helper.py +++ b/InvenTree/web/templatetags/spa_helper.py @@ -3,6 +3,7 @@ import json from logging import getLogger from pathlib import Path +from typing import Union from django import template from django.conf import settings @@ -15,30 +16,44 @@ FRONTEND_SETTINGS = json.dumps(settings.FRONTEND_SETTINGS) @register.simple_tag -def spa_bundle(): +def spa_bundle(manifest_path: Union[str, Path] = '', app: str = 'web'): """Render SPA bundle.""" - manifest = Path(__file__).parent.parent.joinpath("static/web/manifest.json") + def get_url(file: str) -> str: + """Get static url for file.""" + return f"{settings.STATIC_URL}{app}/{file}" + + if manifest_path == '': + manifest_path = Path(__file__).parent.parent.joinpath("static/web/manifest.json") + manifest = Path(manifest_path) if not manifest.exists(): logger.error("Manifest file not found") return - manifest_data = json.load(manifest.open()) - index = manifest_data.get("index.html") - css_index = manifest_data.get("index.css") + try: + manifest_data = json.load(manifest.open()) + except (TypeError, json.decoder.JSONDecodeError): + logger.exception("Failed to parse manifest file") + return + return_string = "" + # CSS (based on index.css file as entrypoint) + css_index = manifest_data.get("index.css") + if css_index: + return_string += f'' + + # JS (based on index.html file as entrypoint) + index = manifest_data.get("index.html") dynamic_files = index.get("dynamicImports", []) imports_files = "".join( [ - f'' + f'' for file in dynamic_files ] ) + return_string += f'{imports_files}' - return mark_safe( - f""" - {imports_files}""" - ) + return mark_safe(return_string) @register.simple_tag