예제 #1
0
def parseContent(content, info=None):
    if not content:
        return None

    if info is None:
        info = {}

    if isinstance(content, str):
        return parse_content_django(content, info=info)

    def get_nested_val(dct, key):
        for k in key.split('.'):
            try:
                dct = dct[k]
            except KeyError:
                return None
        return dct

    arr = []
    for c in content:
        if 'text' in c:
            arr.append(make_unicode(c['text']))
        elif 'var' in c:
            var = c['var']
            if '.' in var:
                val = get_nested_val(copy.deepcopy(info), var)
            else:
                val = info.get(var) or info.get(var.split('__')[0])

            if val is None:
                val = c.get('default')

            if val is None and c.get('hide_content_if_missing', False):
                return None

            if var == '_UUID':
                val = str(uuid.uuid4())

            if var == '_NOW':
                val = timezone.now()

            if var.endswith('__LOCALTIME'):
                val = timezone.localtime(val)

            if var.endswith('__DATE'):
                val = val.strftime('%Y-%m-%d')

            if isinstance(val, datetime.datetime):
                val = val.isoformat()

            if val is not None:
                arr.append(make_unicode(val))

    return ''.join(arr)
예제 #2
0
def parse_content_django(content, info=None, unicode_error=False, syntax_error=False):
    for k, v in info.items():
        if (isinstance(v, (str, bytes))):
            info[k] = make_unicode(v)

    c = Context(info)
    try:
        t = Template(content)
    except TemplateSyntaxError:
        if syntax_error:
            raise

        def remove_underscore_prefix(d):
            new = {}
            for k, v in d.items():
                if isinstance(v, dict):
                    v = remove_underscore_prefix(v)
                if k.startswith('_'):
                    new[k[1:]] = v
                else:
                    new[k] = v
            return new
        new_data = remove_underscore_prefix(info)
        regcontent = leading_underscore_tag_re.sub(r'{{\1}}', content)
        return parse_content_django(regcontent, info=new_data, syntax_error=True)

    return t.render(c)