def display_context(doc):
    """Create a Jinja context for display"""
    from rowgenerators.exceptions import DownloadError

    context = {s.name.lower(): s.as_dict() for s in doc if s.name.lower() != 'schema'}

    #import json
    #print(json.dumps(context, indent=4))

    mandatory_sections = ['documentation', 'contacts']

    # Remove section names
    deletes = []
    for k,v in context.items():
        try:
            del v['@value']
        except KeyError:
            pass # Doesn't have the value
        except TypeError:
            # Is actually completely empty, and has a scalar value. Delete and re-create
            deletes.append(k)

        if isinstance(v, str): # Shouldn't ever happen, but who knows ?
            deletes.append(k)

    for d in deletes:
        try:
            del context[d]
        except KeyError:
            # Fails in TravisCI, no idea why.
            pass

    for ms in mandatory_sections:
        if not ms in context:
            context[ms] = {}

    # Load inline documentation
    inline = ''

    for d in context.get('documentation',{}).get('documentation',[]):

        u = parse_app_url(d['url'])

        if u.target_format == 'md':  # The README.md file
            inline = ''
            if u.proto == 'file':
                # File really ought to be relative
                t = doc.package_url.join_target(u).get_resource().get_target()
            else:
                try:
                    t = u.get_resource().get_target()
                except DownloadError as e:
                    raise e


            try:
                with open(t.fspath) as f:
                    inline += f.read()

            except FileNotFoundError:
                pass

            del d['title'] # Will cause it to be ignored in next section

    # Strip off the leading title, if it exists, because it will be re-applied
    # by the templates
    import re

    lines = inline.strip().splitlines()
    if lines and lines[0].startswith('# '):
        lines = lines[1:]

    context['inline_doc'] = '\n'.join(lines)

    # Convert doc section
    doc_links = {}
    images = {}
    for term_name, terms in context['documentation'].items():
        if term_name == 'note':
            context['notes'] = terms
        else:
            for i, term in enumerate(terms):
                try:
                    if term_name == 'image':
                        images[term['title']] = term
                    else:
                        doc_links[term['title']] = term
                except AttributeError: # A scalar
                    pass # There should not be any scalars in the documentation section
                except KeyError:
                    pass # ignore entries without titles
                except TypeError:
                    pass # Also probably a ascalar

    context['doc_links'] = doc_links
    context['images'] = images

    del context['documentation']

    #
    # Update contacts

    origin = None
    for term_name, terms in context['contacts'].items():
        if isinstance(terms, dict):
            origin = terms # Origin is a scalar in roort, must be converted to sequence here
        else:
            for t in terms:
                try:
                    t.update(process_contact(t))
                except AttributeError:
                    pass # Probably got a scalar
    if origin:
        origin.update(process_contact(origin))
        context['contacts']['origin'] = [origin]


    # For resources and references, convert scalars into lists of dicts, which are the
    # default for Datafiles and References.

    for section in ('references', 'resources'):
        for term_key, term_vals in context.get(section,{}).items():
            if isinstance(term_vals, dict):
                if '@value' in term_vals:
                    term_vals['url'] = term_vals['@value']
                    del term_vals['@value']
                new_term_vals = [term_vals]
            elif isinstance(term_vals, list):
                new_term_vals = None
            else:
                new_term_vals = [ {'url': term_vals, 'name': term_vals}]

            if new_term_vals:
                context[section][term_key] = new_term_vals

    context['distributions'] = {}
    for dist in doc.find('Root.Distribution'):
        context['distributions'][dist.type] = dist.value

    if doc.find('Root.Giturl'):
        context['distributions']['source'] = doc.get_value('Root.Giturl')

    return context