Mercurial > hg
comparison mercurial/templater.py @ 21846:8f23f8096606
templater: introduce word function
This function allows returning only the nth "word" from a string. By default
a string is split as by Python's split() function default, but an optional
third parameter can also override what string the string is split by.
author | Ryan McElroy <rmcelroy@fb.com> |
---|---|
date | Thu, 12 Jun 2014 18:02:23 -0700 |
parents | 028a48105191 |
children | 2896d450fec4 |
comparison
equal
deleted
inserted
replaced
21845:04f5b5e3792e | 21846:8f23f8096606 |
---|---|
475 if text.startswith(patn): | 475 if text.startswith(patn): |
476 return text | 476 return text |
477 return '' | 477 return '' |
478 | 478 |
479 | 479 |
480 def word(context, mapping, args): | |
481 """return nth word from a string""" | |
482 if not (2 <= len(args) <= 3): | |
483 raise error.ParseError(_("word expects two or three arguments, got %d") | |
484 % len(args)) | |
485 | |
486 num = int(stringify(args[0][0](context, mapping, args[0][1]))) | |
487 text = stringify(args[1][0](context, mapping, args[1][1])) | |
488 if len(args) == 3: | |
489 splitter = stringify(args[2][0](context, mapping, args[2][1])) | |
490 else: | |
491 splitter = None | |
492 | |
493 tokens = text.split(splitter) | |
494 if num >= len(tokens): | |
495 return '' | |
496 else: | |
497 return tokens[num] | |
498 | |
480 methods = { | 499 methods = { |
481 "string": lambda e, c: (runstring, e[1]), | 500 "string": lambda e, c: (runstring, e[1]), |
482 "rawstring": lambda e, c: (runrawstring, e[1]), | 501 "rawstring": lambda e, c: (runrawstring, e[1]), |
483 "symbol": lambda e, c: (runsymbol, e[1]), | 502 "symbol": lambda e, c: (runsymbol, e[1]), |
484 "group": lambda e, c: compileexp(e[1], c), | 503 "group": lambda e, c: compileexp(e[1], c), |
502 "rstdoc": rstdoc, | 521 "rstdoc": rstdoc, |
503 "shortest": shortest, | 522 "shortest": shortest, |
504 "startswith": startswith, | 523 "startswith": startswith, |
505 "strip": strip, | 524 "strip": strip, |
506 "sub": sub, | 525 "sub": sub, |
526 "word": word, | |
507 } | 527 } |
508 | 528 |
509 # template engine | 529 # template engine |
510 | 530 |
511 path = ['templates', '../templates'] | 531 path = ['templates', '../templates'] |