changeset 3105:eec0c25c796b

core (memory/params): new "makeOptions" method to easily create options XML from a dict
author Goffi <goffi@goffi.org>
date Fri, 03 Jan 2020 13:20:45 +0100
parents 118d91c932a7
children 7f7cdc6ecfd8
files sat/memory/params.py
diffstat 1 files changed, 27 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/sat/memory/params.py	Mon Dec 30 20:59:46 2019 +0100
+++ b/sat/memory/params.py	Fri Jan 03 13:20:45 2020 +0100
@@ -31,6 +31,7 @@
 from twisted.words.xish import domish
 from twisted.words.protocols.jabber import jid
 from sat.tools.xml_tools import paramsXML2XMLUI, getText
+from xml.sax.saxutils import quoteattr
 
 # TODO: params should be rewritten using Twisted directly instead of minidom
 #       general params should be linked to sat.conf and kept synchronised
@@ -1132,3 +1133,29 @@
         if not app or not node.hasAttribute("app"):
             return True
         return node.getAttribute("app") == app
+
+
+def makeOptions(options, selected=None):
+    """Create option XML form dictionary
+
+    @param options(dict): option's name => option's label map
+    @param selected(None, str): value of selected option
+        None to use first value
+    @return (str): XML to use in parameters
+    """
+    str_list = []
+    if selected is None:
+        selected = next(iter(options.keys()))
+    selected_found = False
+    for value, label in options.items():
+        if value == selected:
+            selected = 'selected="true"'
+            selected_found = True
+        else:
+            selected = ''
+        str_list.append(
+            f'<option value={quoteattr(value)} label={quoteattr(label)} {selected}/>'
+        )
+    if not selected_found:
+        raise ValueError(f"selected value ({selected}) not found in options")
+    return '\n'.join(str_list)