diff mercurial/templater.py @ 29085:df838803c1d4

templater: add separate() template function A pretty common pattern in templates is adding conditional separators like so: {node}{if(bookmarks, " {bookmarks}")}{if(tags, " {tags}")} With this patch, the above can be simplified to: {separate(" ", node, bookmarks, tags)} The function is similar to the already existing join(), but with a few differences: * separate() skips empty arguments * join() expects a single list argument, while separate() expects each item as a separate argument * separate() takes the separator first in order to allow a variable number of arguments after it
author Martin von Zweigbergk <martinvonz@google.com>
date Tue, 03 May 2016 09:49:54 -0700
parents d813132ea361
children 84ef4517de03
line wrap: on
line diff
--- a/mercurial/templater.py	Wed May 04 21:01:49 2016 -0400
+++ b/mercurial/templater.py	Tue May 03 09:49:54 2016 -0700
@@ -724,6 +724,25 @@
 
     return minirst.format(text, style=style, keep=['verbose'])
 
+@templatefunc('separate(sep, args)')
+def separate(context, mapping, args):
+    """Add a separator between non-empty arguments."""
+    if not args:
+        # i18n: "separate" is a keyword
+        raise error.ParseError(_("separate expects at least one argument"))
+
+    sep = evalstring(context, mapping, args[0])
+    first = True
+    for arg in args[1:]:
+        argstr = evalstring(context, mapping, arg)
+        if not argstr:
+            continue
+        if first:
+            first = False
+        else:
+            yield sep
+        yield argstr
+
 @templatefunc('shortest(node, minlength=4)')
 def shortest(context, mapping, args):
     """Obtain the shortest representation of