Last active
December 29, 2015 00:59
-
-
Save draganHR/7589517 to your computer and use it in GitHub Desktop.
Render template by using Django template system.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
""" | |
render.py | |
Render template by using Django template system. | |
Copyright (c) 2013 Dragan Bosnjak <[email protected]> | |
License: MIT | |
""" | |
import argparse | |
from django import template | |
from django.utils.safestring import mark_safe | |
from django.conf import settings | |
def main(): | |
settings.configure() | |
parser = argparse.ArgumentParser(description='Render template by using Django template system.', | |
epilog='Example: render.py -s "{{ greeting }}, my name is {{ name }}." greeting "Hi" name "Ron Burgundy"' | |
) | |
parser.add_argument('-s', '--string', type=str, help="Template as a string") | |
parser.add_argument('-i', '--input', type=str, help="Input file name") | |
parser.add_argument('-o', '--output', type=str, help="Output file name") | |
parser.add_argument('-f', '--autoescape-off', dest='autoescape_off', action='store_true', help="Prevent automatic HTML escaping") | |
parser.add_argument('context', type=str, nargs=argparse.REMAINDER, help='List of variable names and values separated by spaces', metavar='NAME VALUE') | |
args = parser.parse_args() | |
context = template.Context() | |
if args.context: | |
while args.context: | |
key = args.context.pop(0) | |
if not args.context: | |
parser.error('Invalid context: missing value for key "%s"!' % key) | |
if args.autoescape_off: | |
context[key] = mark_safe(args.context.pop(0)) | |
else: | |
context[key] = args.context.pop(0) | |
if bool(args.string) == bool(args.input): | |
parser.error('You must specifiy either input or string argument!') | |
elif args.input: | |
tpl = open(args.input, "r").read() | |
else: | |
tpl = args.string | |
result = template.Template(tpl).render(context) | |
if args.output: | |
open(args.output, 'w').write(result) | |
else: | |
print result | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment