Source code for uw.web.html.join

"""Routines for rendering lists of items as HTML.

Contains a routine for rendering a list as a typical English sentence, and
one for rendering a list with a specified separator between the items.
"""

from functools import partial

from ll.xist import xsc

[docs]def english_join_flex (jointext, *items): """Join a list of items in typical English style. :param str jointext: The conjunction ("and" or "or") to be used to join the items. :param \*items: the list of HTML fragments to join. This is for putting together lists of items in English text. For two items, they are simply joined by putting the conjunction between them. For more than two items, they are joined by commas, and the conjunction is inserted before the last one. A single item is returned unmodified. If no items are supplied, the result is None. The items are preprocessed by removing any items that are None. """ items = [x for x in items if x is not None] result = [] if len (items) == 0: return None elif len (items) == 1: return items[0] elif len (items) == 2: return xsc.Frag (items[0], ' ', jointext, ' ', items[1]) else: result = [] for i, item in reversed (list (enumerate (reversed (items)))): result.append (item) if i: result.append (', ') if i == 1: result.append (jointext) result.append (' ') return xsc.Frag (result)
english_join_or = partial (english_join_flex, 'or') english_join_and = partial (english_join_flex, 'and') english_join = english_join_and
[docs]def html_join (items, sep=None): """Join a list of HTML items with the specified HTML separator. :param items: the list of HTML fragments to join. :param sep: an HTML fragment to use for the separator, if any. This is for putting together lists of items where a separator is required between each adjacent pair of items. A single item is returned unmodified. If no items are supplied, the result is None. The items are preprocessed by removing any items that are None. """ items = [x for x in items if x is not None] if len (items) == 0: return None elif len (items) == 1: return items[0] else: result = [items[0]] for item in items[1:]: if sep is not None: result.append (sep) result.append (item) return xsc.Frag (result)