Search code examples
code-golf

Golf - Expand Templates In Text File


Golf - implement a simple templating scheme.

Expansions are:

  • %KEY% -> VALUE
  • %% -> %

Command line arguments:

  • ARG1: dictionary file, formatted in the key=value style as in example
  • ARG2: template file

Here my not quite golf attempt(python): 261 chars.

import sys
dd = dict([ll.split("=",2) for ll in open( sys.argv[1],'r') if len(ll.split("=", 2)) == 2])
tt = "".join([ ll for ll in open( sys.argv[2],'r')])
sys.stdout.write("".join([(((s == "") and "%") or ((s in dd) and dd[s]) or s) for s in tt.split("%")]))

DICT

NAME=MyName
ODDS=100

TEMPLATE

I, %NAME% am %ODDS% %% sure that that this a waste of time.

RESULT

I, My Name am 100 % sure that this is a waste of time.

Yes, I realize this is a defective templating system, "snaps" for a shorter and better implementation.


Solution

  • In Python, you could leverage the inbuilt string formatting to make it shorter. Just needs a little regex hacking to get the syntax to match.

    import sys, re
    sys.stdout.write(re.sub(r'%(.+?)%',r'%(\1)s',open(sys.argv[2]).read())%dict(l.split("=",2) for l in open(sys.argv[1],'r')))
    

    Down to 139 bytes. (Though perhaps the args/file-IO stuff shouldn't really be part of a golf challenge?)