From 0c0e61432d2d4d44deb2c7d089e14217c448dad6 Mon Sep 17 00:00:00 2001 From: Oliver Date: Mon, 7 Nov 2022 21:24:25 +1100 Subject: [PATCH] Adds a report template tag for dict access (#3905) * Adds a report template tag for dict access (cherry picked from commit 7df2f0f878e312a6f94a2c24304643cde91012de) * Add unit test for new template tag --- InvenTree/report/templatetags/report.py | 14 ++++++++++++++ InvenTree/report/tests.py | 13 +++++++++++++ 2 files changed, 27 insertions(+) diff --git a/InvenTree/report/templatetags/report.py b/InvenTree/report/templatetags/report.py index ac848081b9..11e12f288a 100644 --- a/InvenTree/report/templatetags/report.py +++ b/InvenTree/report/templatetags/report.py @@ -18,6 +18,20 @@ register = template.Library() logger = logging.getLogger('inventree') +@register.simple_tag() +def getkey(value: dict, arg): + """Perform key lookup in the provided dict object. + + This function is provided to get around template rendering limitations. + Ref: https://stackoverflow.com/questions/1906129/dict-keys-with-spaces-in-django-templates + + Arguments: + value: A python dict object + arg: The 'key' to be found within the dict + """ + return value[arg] + + @register.simple_tag() def asset(filename): """Return fully-qualified path for an upload report asset file. diff --git a/InvenTree/report/tests.py b/InvenTree/report/tests.py index 8361be45e8..7b1b9759e1 100644 --- a/InvenTree/report/tests.py +++ b/InvenTree/report/tests.py @@ -29,6 +29,19 @@ class ReportTagTest(TestCase): """Enable or disable debug mode for reports""" InvenTreeSetting.set_setting('REPORT_DEBUG_MODE', value, change_user=None) + def test_getkey(self): + """Tests for the 'getkey' template tag""" + + data = { + 'hello': 'world', + 'foo': 'bar', + 'with spaces': 'withoutspaces', + 1: 2, + } + + for k, v in data.items(): + self.assertEqual(report_tags.getkey(data, k), v) + def test_asset(self): """Tests for asset files"""