Ejemplo n.º 1
0
def main():
    options = parse_opts()
    if options['json_template'] is None:
        print('No JSON template', file=sys.stderr)
        usage()
        sys.exit(1)
    if options['json'] is None:
        print('No JSON object', file=sys.stderr)
        usage()
        sys.exit(1)

    template = read_file(options['json_template'])
    json_object = read_file(options['json'])
    try:
        json_dict = json.loads(json_object)
    except ValueError as e:
        print('Invalid JSON: %s' % e, file=sys.stderr)
        sys.exit(1)

    if options['debug']:
        print(template, end='', file=sys.stderr)
        print(json_object, end='', file=sys.stderr)
        print(json_dict, end='', file=sys.stderr)

    fmt = formatters.Fmt()

    # XXX exceptions?
    jt = jsontemplate.FromString(template, more_formatters=fmt.formatters())
    s = jt.expand(json_dict)
    print(s, end='')
Ejemplo n.º 2
0
def add_summary(bug, bug_mapping):
    """Add the summary information to the bug."""
    t = jsontemplate.FromString(BUG_SUMMARY_TEMPLATE)
    bug['duplicate_of'] = bug['duplicate_of'] in bug_mapping and bug_mapping[
        bug['duplicate_of']] or None
    bug['duplicates'] = [
        bug_mapping[x] for x in bug['duplicates'] if x in bug_mapping
    ]
    bug['description'] = bug['description'] + '\n' + t.expand(bug)
    return bug
Ejemplo n.º 3
0
def main(argv):
    """Returns an exit code."""

    options = cmdapp.ParseArgv(argv[1:], PARAMS)

    if options.files:
        template_str = open(options.template).read()
        dictionary = open(options.json).read()
    else:
        template_str = options.template
        dictionary = options.json

    dictionary = json.loads(dictionary)

    if options.more_formatters:
        more_formatters = formatters.PythonPercentFormat
    else:
        more_formatters = lambda x: None

    t = jsontemplate.FromString(template_str, more_formatters=more_formatters)
    sys.stdout.write(t.expand(dictionary))
Ejemplo n.º 4
0
def BlogPosts(directory):
    assert directory.endswith('/')

    posts = []
    for filename in glob.glob(directory + '*.html.jsont'):
        title = filename[len(directory):-len('.html.jsont')].replace('-', ' ')
        outfilename = filename[:-len('.jsont')]

        blog_template = open(filename).read()

        dictionary = {}
        try:
            body = jsontemplate.FromString(blog_template).expand(dictionary)
        except jsontemplate.EvaluationError, e:
            print >> sys.stderr, 'Error expanding %s' % filename
            raise

        posts.append(
            dict(filename=filename,
                 title=title,
                 body=body,
                 outfilename=outfilename,
                 pretty_print=pretty_print))
Ejemplo n.º 5
0
    else:
        template_file = opts['<template-file>']
        if template_file:
            try:
                f = open(template_file)
            except IOError, e:
                raise RuntimeError(e)
            template_str = f.read()
        else:
            raise UsageError("A template file or inline template is required.")

    # TODO: add more?
    more_formatters = formatters.PythonPercentFormat
    t = jsontemplate.FromString(
        template_str,
        more_formatters=more_formatters,
        # TODO: add more?
        more_predicates=None)

    dictionary = json.load(sys.stdin)
    s = t.expand(dictionary)
    sys.stdout.write(s.encode('utf-8'))
    return 0


if __name__ == '__main__':
    try:
        sys.exit(main(sys.argv))
    except RuntimeError, e:
        print >> sys.stderr, 'jsont: %s' % e.args[0]
        sys.exit(1)
        'The_Simpsons_Characters_Picture_Gallery/Ralph_Wiggum.gif',
    },
}

# Define a template for the user profile.  This is the thing we're going to
# reuse across multiple pages.
#
# (This is also an example of the FromString construction method, which allows
# compilation options in the template string itself).

USER_PROFILE_TEMPLATE = jsontemplate.FromString("""\
default-formatter: html

<center> <!-- Good old center tag -->
  <img src="{pic_url}" /><br>
  <b>
  <a href="http://google.com/search?q={name|url-param-value}">
  {name}
  </a>
  </b>
</center>
""")

# Now we define a wrapper for templates that can render user profiles.
#
# To do this, we must specify a *function* MoreFormatters that maps formatter
# names (strings in the template) to other functions (which take *JSON node*
# values and return strings to be output in the template).


class MoreFormatters(object):