Esempio n. 1
0
    def load_template(self, template_name, template_dirs=None):
        key = template_name
        if template_dirs:
            # If template directories were specified, use a hash to differentiate
            key = '-'.join([template_name, hashlib.sha1('|'.join(template_dirs)).hexdigest()])

        
        if settings.DEBUG or key not in self.template_cache:

            if os.path.splitext(template_name)[1] in ('.jade',):
                try:
                    source, display_name = self.load_template_source(template_name, template_dirs)
                    source=process(source,filename=template_name,compiler=Compiler)
                    origin = make_origin(display_name, self.load_template_source, template_name, template_dirs)
                    template = get_template_from_string(source, origin, template_name)
                except NotImplementedError:
                    template, origin = self.find_template(template_name, template_dirs)
            else:
                template, origin = self.find_template(template_name, template_dirs)
            if not hasattr(template, 'render'):
                try:
                    template = get_template_from_string(process(source,filename=template_name,compiler=Compiler), origin, template_name)
                except TemplateDoesNotExist:
                    # If compiling the template we found raises TemplateDoesNotExist,
                    # back off to returning he source and display name for the template
                    # we were asked to load. This allows for correct identification (later)
                    # of the actual template that does not exist.
                    return template, origin
            self.template_cache[key] = template
        return self.template_cache[key], None
Esempio n. 2
0
    def load_template(self, template_name, template_dirs=None):
        key = template_name
        if template_dirs:
            # If template directories were specified, use a hash to differentiate
            key = '-'.join([template_name, hashlib.sha1('|'.join(template_dirs)).hexdigest()])

        
        if settings.DEBUG or key not in self.template_cache:

            if os.path.splitext(template_name)[1] in ('.jade',):
                source, display_name = self.load_template_source(template_name, template_dirs)
                source=process(source,filename=template_name,compiler=Compiler)
                origin = make_origin(display_name, self.load_template_source, template_name, template_dirs)
                template = get_template_from_string(source, origin, template_name)
            else:
                template, origin = self.find_template(template_name, template_dirs)
            if not hasattr(template, 'render'):
                try:
                    template = get_template_from_string(process(source,filename=template_name,compiler=Compiler), origin, template_name)
                except TemplateDoesNotExist:
                    # If compiling the template we found raises TemplateDoesNotExist,
                    # back off to returning he source and display name for the template
                    # we were asked to load. This allows for correct identification (later)
                    # of the actual template that does not exist.
                    return template, origin
            self.template_cache[key] = template
        return self.template_cache[key], None
Esempio n. 3
0
    def django_process(str):
        compiled = process(str, filename=None, compiler=DjangoCompiler)
        print compiled
        t = django.template.Template(compiled)

        ctx = django.template.Context()
        return t.render(ctx)
def upgrade():
    op.add_column('application_template', sa.Column('jinja2', sa.Text))
    op.add_column('application_template', sa.Column('key', sa.String(255)))


    meta = sa.MetaData()
    table = sa.schema.Table(
        'application_template', meta,
        sa.Column('id', sa.BigInteger, primary_key=True),
        sa.Column('key', sa.String(255)),
        sa.Column('jinja2', sa.Text)
    )

    # converting original jade template_source into jinja2 preprocessed source
    conn = op.get_bind()
    rows = conn.execute('select id, template_key, template_source from application_template')
    for row in rows:
        rid = row[0]
        name = row[1]
        source = row[2]
        results = process(source,filename=name,compiler=Compiler)
        where = 'id=%d' % rid
        update_expression = sa.sql.expression.update(
            table, whereclause=where,
            values={
                'jinja2': results,
                'key': name
            }
        )
        conn.execute(update_expression)
Esempio n. 5
0
 def preprocess(self, source, name, filename=None):
     if (not name or
        (name and not os.path.splitext(name)[1] in self.file_extensions)):
         msg = "return {}".format(name)
         logging.info(msg)
         return source
     return process(source,filename=name,compiler=Compiler,**self.options)
Esempio n. 6
0
    def django_process(src, filename):
        compiled = process(src, filename=filename,compiler = DjangoCompiler)
        print compiled
        t = django.template.Template(compiled)

        ctx = django.template.Context()
        return t.render(ctx)
Esempio n. 7
0
    def django_process(str):
        compiled = process(str,filename=None,compiler = DjangoCompiler)
        print(compiled)
        t = django.template.Template(compiled)

        ctx = django.template.Context()
        return t.render(ctx)
Esempio n. 8
0
 def preprocess(self, source, name, filename=None):
     if name and not os.path.splitext(name)[1] in self.file_extensions:
         return source
     return process(source,
                    filename=name,
                    compiler=Compiler,
                    **self.options)
Esempio n. 9
0
 def templatize(src, origin=None):
     src = to_text(src, settings.FILE_CHARSET)
     if origin.endswith(".jade"):
         html = process(src,compiler=Compiler)
     else:
         html = src
     return func(html, origin)
Esempio n. 10
0
    def django_process(src, filename):
        compiled = process(src, filename=filename, compiler=DjangoCompiler)
        print(compiled)
        t = django.template.Template(compiled)

        ctx = django.template.Context()
        return t.render(ctx)
Esempio n. 11
0
 def templatize(src, origin=None):
     src = to_text(src, settings.FILE_CHARSET)
     if origin.endswith(".jade"):
         html = process(src,compiler=Compiler)
     else:
         html = src
     return func(html, origin)
Esempio n. 12
0
def convert_file():
    support_compilers_list = ['django', 'jinja', 'underscore', 'mako', 'tornado', 'html']
    available_compilers = {}
    for i in support_compilers_list:
        try:
            compiler_class = __import__('pyjade.ext.%s' % i, fromlist=['pyjade']).Compiler
        except ImportError as e:
            logging.warning(e)
        else:
            available_compilers[i] = compiler_class

    usage = "usage: %prog [options] [file [output]]"
    parser = OptionParser(usage)
    parser.add_option("-o", "--output", dest="output",
                    help="Write output to FILE", metavar="FILE")
    # use a default compiler here to sidestep making a particular
    # compiler absolutely necessary (ex. django)
    default_compiler = sorted(available_compilers.keys())[0]
    parser.add_option("-c", "--compiler", dest="compiler",
                    choices=list(available_compilers.keys()),
                    default=default_compiler,
                    type="choice",
                    help=("COMPILER must be one of %s, default is %s" %
                          (', '.join(list(available_compilers.keys())), default_compiler)))
    parser.add_option("-e", "--ext", dest="extension",
                      help="Set import/extends default file extension",
                      metavar="FILE")

    options, args = parser.parse_args()

    file_output = options.output or (args[1] if len(args) > 1 else None)
    compiler = options.compiler

    if options.extension:
        extension = '.%s' % options.extension
    elif options.output:
        extension = os.path.splitext(options.output)[1]
    else:
        extension = None

    if compiler in available_compilers:
        import six
        if len(args) >= 1:
            template = codecs.open(args[0], 'r', encoding='utf-8').read()
        elif six.PY3:
            template = sys.stdin.read()
        else:
            template = codecs.getreader('utf-8')(sys.stdin).read()
        output = process(template, compiler=available_compilers[compiler],
                         staticAttrs=True, extension=extension)
        if file_output:
            outfile = codecs.open(file_output, 'w', encoding='utf-8')
            outfile.write(output)
        elif six.PY3:
            sys.stdout.write(output)
        else:
            codecs.getwriter('utf-8')(sys.stdout).write(output)
    else:
        raise Exception('You must have %s installed!' % compiler)
Esempio n. 13
0
def convert_file():
    support_compilers_list = ['django', 'jinja', 'underscore', 'mako', 'tornado', 'html']
    available_compilers = {}
    for i in support_compilers_list:
        try:
            compiler_class = __import__('pyjade.ext.%s' % i, fromlist=['pyjade']).Compiler
        except ImportError as e:
            logging.warning(e)
        else:
            available_compilers[i] = compiler_class

    usage = "usage: %prog [options] [file [output]]"
    parser = OptionParser(usage)
    parser.add_option("-o", "--output", dest="output",
                    help="Write output to FILE", metavar="FILE")
    # use a default compiler here to sidestep making a particular
    # compiler absolutely necessary (ex. django)
    default_compiler = sorted(available_compilers.keys())[0]
    parser.add_option("-c", "--compiler", dest="compiler",
                    choices=list(available_compilers.keys()),
                    default=default_compiler,
                    type="choice",
                    help=("COMPILER must be one of %s, default is %s" %
                          (', '.join(list(available_compilers.keys())), default_compiler)))
    parser.add_option("-e", "--ext", dest="extension",
                      help="Set import/extends default file extension",
                      metavar="FILE")

    options, args = parser.parse_args()

    file_output = options.output or (args[1] if len(args) > 1 else None)
    compiler = options.compiler

    if options.extension:
        extension = '.%s' % options.extension
    elif options.output:
        extension = os.path.splitext(options.output)[1]
    else:
        extension = None

    if compiler in available_compilers:
        import six
        if len(args) >= 1:
            template = codecs.open(args[0], 'r', encoding='utf-8').read()
        elif six.PY3:
            template = sys.stdin.read()
        else:
            template = codecs.getreader('utf-8')(sys.stdin).read()
        output = process(template, compiler=available_compilers[compiler],
                         staticAttrs=True, extension=extension)
        if file_output:
            outfile = codecs.open(file_output, 'w', encoding='utf-8')
            outfile.write(output)
        elif six.PY3:
            sys.stdout.write(output)
        else:
            codecs.getwriter('utf-8')(sys.stdout).write(output)
    else:
        raise Exception('You must have %s installed!' % compiler)
Esempio n. 14
0
    def __init__(self, template_string, name="<string>", *args, **kwargs):
        is_jade = name.endswith(".jade")
        if is_jade:
            template_string = process(template_string, filename=name, compiler=Compiler)

        super(Template, self).__init__(template_string, name, *args, **kwargs)
        if is_jade:
            self.namespace.update({ATTRS_FUNC: attrs, ESCAPE_FUNC: escape, ITER_FUNC: iteration})
def _convert(src, dst):
    template = codecs.open(src, "r", encoding="utf-8").read()
    output = process(template, compiler=UnderscoreCompiler)
    outfile = codecs.open(dst, "w", encoding="utf-8")
    outfile.write(output)
    outfile.close()

    print 'compiled "%s" into "%s"' % (src, dst)
Esempio n. 16
0
def convert_file(input_file, output_file):
    with codecs.open(input_file, "r", encoding="utf-8") as rf:
        output = process(rf.read(),
                         compiler=Compiler,
                         staticAttrs=True,
                         extension=None)
        with codecs.open(output_file, "w", encoding="utf-8") as wf:
            wf.write(output)
Esempio n. 17
0
 def preprocess(self, source, name, filename=None):
     if (not name or
         (name and not os.path.splitext(name)[1] in self.file_extensions)):
         return source
     return process(source,
                    filename=name,
                    compiler=JinjaAutoescapeCompiler,
                    **self.options)
Esempio n. 18
0
 def _convert_jade(cls, jade_file):
     """
         读取 jade 文件并转化为 html 标签形式
     """
     with codecs.open(jade_file, "r", encoding="utf-8") as rf:
         return process(rf.read(),
                        compiler=Compiler,
                        staticAttrs=True,
                        extension=None)
Esempio n. 19
0
    def preprocess(self, source, name, filename=None):
        if name and not os.path.splitext(name)[1] in self.environment.jade_file_extensions:
            return source

        return process(source,filename=name,compiler=Compiler)
        # parser = Parser(source,filename=name)
        # block = parser.parse()
        # compiler = Compiler(block)
        # return compiler.compile()
        # procesed= process(source,name)
        # print procesed
        # return procesed
Esempio n. 20
0
def convert_file():
    support_compilers_list = ['django', 'jinja', 'underscore', 'mako', 'tornado']
    available_compilers = {}
    for i in support_compilers_list:
        try:
            compiler_class = __import__('pyjade.ext.{0}'.format(i), fromlist=['pyjade']).Compiler
        except ImportError as e:
            logging.warning(e)
        else:
            available_compilers[i] = compiler_class

    usage = "usage: %prog [options] file [output]"
    parser = OptionParser(usage)
    parser.add_option("-o", "--output", dest="output",
                      help="Write output to FILE", metavar="FILE")
    # use a default compiler here to sidestep making a particular
    # compiler absolutely necessary (ex. django)
    default_compiler = sorted(available_compilers.keys())[0]
    parser.add_option("-c", "--compiler", dest="compiler",
                      choices=list(available_compilers.keys()),
                      default=default_compiler,
                      type="choice",
                      help=("COMPILER must be one of {0}, default is {1}"
                            .format(','.join(list(available_compilers.keys())), default_compiler)))
    parser.add_option("-e", "--ext", dest="extension",
                      help="Set import/extends default file extension",
                      metavar="FILE")

    options, args = parser.parse_args()
    if len(args) < 1:
        print("Specify the input file as the first argument.")
        exit()
    file_output = options.output or (args[1] if len(args) > 1 else None)
    compiler = options.compiler

    if options.extension:
        extension = '.{0}'.format(options.extension)
    elif options.output:
        extension = os.path.splitext(options.output)[1]
    else:
        extension = None

    if compiler in available_compilers:
        template = codecs.open(args[0], 'r', encoding='utf-8').read()
        output = process(template, compiler=available_compilers[compiler],
                         staticAttrs=True, extension=extension)
        if file_output:
            outfile = codecs.open(file_output, 'w', encoding='utf-8')
            outfile.write(output)
        else:
            print(output)
    else:
        raise Exception('You must have {0} installed!'.format(compiler))
Esempio n. 21
0
def convert_file():
    import codecs
    aviable_compilers = {}
    try:
        from pyjade.ext.django import Compiler as DjancoCompiler
        aviable_compilers['django'] = DjancoCompiler
    except:
        pass
    try:
        from pyjade.ext.jinja import Compiler as JinjaCompiler
        aviable_compilers['jinja'] = JinjaCompiler
    except:
        pass
    try:
        from pyjade.ext.underscore import Compiler as UnderscoreCompiler
        aviable_compilers['underscore'] = UnderscoreCompiler
    except:
        pass
    try:
        from pyjade.ext.mako import Compiler as MakoCompiler
        aviable_compilers['mako'] = MakoCompiler
    except:
        pass
    from optparse import OptionParser
    usage = "usage: %prog [options] file [output]"
    parser = OptionParser(usage)
    parser.add_option("-o", "--output", dest="output",
                      help="write output to FILE", metavar="FILE")
    parser.add_option("-c", "--compiler", dest="compiler",
                        choices=['django', 'jinja', 'mako', 'underscore',],
                        default='django',
                        type="choice",
                      help="COMPILER must be django (default), jinja, underscore or mako ")
    # parser.add_option("-q", "--quiet",
    #                   action="store_false", dest="verbose", default=True,
    #                   help="don't print status messages to stdout")
    (options, args) = parser.parse_args()
    if len(args)<1:
        print "Specify the input file as the first argument."
        exit()
    file_output = options.output or (args[1] if len(args)>1 else None)
    compiler = options.compiler
    if compiler in aviable_compilers:
        template = codecs.open(args[0], 'r', encoding='utf-8').read()
        output = process(template,compiler=aviable_compilers[compiler])
        if file_output:
            outfile = codecs.open(file_output, 'w', encoding='utf-8')
            outfile.write(output)
        else:
            print output
    else:
        raise Exception('You must have %s installed!'%compiler)
Esempio n. 22
0
 def load_template(self, template_name, template_dirs=None):
     if os.path.splitext(str(template_name))[1] in ('.jade',):
         try:
             source, display_name = self.load_template_source(template_name, template_dirs)
             source=process(source,filename=template_name,compiler=Compiler)
             origin = make_origin(display_name, self.load_template_source, template_name, template_dirs)
             template = get_template_from_string(source, origin, template_name)
         except NotImplementedError:
             template, origin = self.find_template(template_name, template_dirs)
     else:
         template, origin = self.find_template(template_name, template_dirs)
     if not hasattr(template, 'render'):
         try:
             template = get_template_from_string(process(source,filename=template_name,compiler=Compiler), origin, template_name)
         except TemplateDoesNotExist:
             # If compiling the template we found raises TemplateDoesNotExist,
             # back off to returning he source and display name for the template
             # we were asked to load. This allows for correct identification (later)
             # of the actual template that does not exist.
             return template, origin
     
     return template, None
Esempio n. 23
0
    def __init__(self, template_string, name="<string>", *args, **kwargs):
        is_jade = name.endswith(".jade")
        if is_jade:
            template_string = process(template_string,
                                      filename=name,
                                      compiler=Compiler)

        super(Template, self).__init__(template_string, name, *args, **kwargs)
        if is_jade:
            self.namespace.update({
                ATTRS_FUNC: attrs,
                ESCAPE_FUNC: escape,
                ITER_FUNC: iteration
            })
Esempio n. 24
0
def convert_jade_to_html(source, hash_key=None, cache_client=None):
    # 计算 cache_key
    if hash_key and cache_client:
        cache_key = 'jade:%s' % hash_key
        cached = cache_client.get(cache_key, zipped=True)
        if cached:
            return cached
    else:
        cache_key = None

    source = to_unicode(source)
    source = source.strip().replace(u'\ufeff', '')  #去除头尾

    source = re.sub(r'\\\r?\n', '', source)  # 多行分割合并成一行的对应

    #source = re.sub(r'\t', '    ', source) # 替换掉 tab 键为空格
    source = beautiful_jade(source)

    source = re.sub(r'((?:^|\n) *)else if ', '\g<1>elif ',
                    source)  # 替换else if->elif

    for func_name in ONE_LINE_FUNCTIONS:
        # 对单行特定函数,先处理为template的语法
        source = re.sub(r'([\r\n] *|^ *)(%s\(.*?\))(?= *[\r\n]|$)' % func_name,
                        '\g<1>{{\g<2>}}',
                        source)  # 对单行的load函数的处理,避免被当成一个TagName

    new_source = process(source, compiler=Compiler)

    # 对头部代码的补充处理
    head_codes_search = re.search(r'<head>.*?</head>', new_source, re.S)
    if head_codes_search and 'set_content_type(' not in new_source:  # 如果有设定content_type的,就不额外处理了
        if not new_source.startswith('<!'):
            new_source = "<!DOCTYPE html>\n" + new_source
        head_codes = head_codes_search.group()
        #if not re.search(r'<link.*?rel=["\']alternate["\']', head_codes, re.I): # 增加feed链接
        #    new_source = new_source.replace('<head>', '<head>%s' % FEED_HTML)
        if not re.search(r'<meta.*?http-equiv=[\'"]content-type[\'"]',
                         head_codes, re.I):  # 增加content_type声明
            new_source = new_source.replace('<head>',
                                            '<head>%s' % CONTENT_TYPE_HTML)

    # cache it
    if cache_key and cache_client:
        cache_client.set(cache_key, new_source, zipped=True)

    return new_source
Esempio n. 25
0
def run_case(case,process):
    global processors
    process = processors[process]
    jade_file = open('cases/%s.jade'%case)
    jade_src = jade_file.read().decode('utf-8')
    jade_file.close()

    html_file = open('cases/%s.html'%case)
    html_src = html_file.read().strip('\n').decode('utf-8')
    html_file.close()
    try:
        processed_jade = process(jade_src).strip('\n')
        print 'PROCESSED\n',processed_jade,len(processed_jade)
        print 'EXPECTED\n',html_src,len(html_src)
        assert processed_jade==html_src
    except CurrentlyNotSupported:
        pass
Esempio n. 26
0
 def render_jade_with_json(self, jade_template_path, json_file_path,
                           template_path_base, base_file):
     logger.debug('Working with jade template %s', jade_template_path)
     tmpl = loader.get_template(jade_template_path)
     if settings.DEBUG:
         logger.debug('Template is: %s',
                      process(open(os.path.join(self.template_path,
                                                jade_template_path)).read()))
     # We need to simulate request middleware but without short-circuiting
     # the response
     request_factory = RequestFactory()
     req = request_factory.get('/%s/%s.html' % (template_path_base,
                                                base_file),
                               data={})
     handler = WSGIHandler()
     handler.load_middleware()
     for middleware_method in handler._request_middleware:
         middleware_method(req)
     # Render the template with a RequestContext
     ctx = RequestContext(req, json.load(open(json_file_path)))
     return tmpl.render(ctx)
Esempio n. 27
0
 def compile(self, base_file_name, path, template_path):
     jade_template_path = os.path.join(template_path,
                                       '%s.jade' % (base_file_name,))
     logger.debug('Working with jade template %s', jade_template_path)
     # Change the pwd to the template's location
     current_pwd = os.getcwd()
     os.chdir(path)
     # Hackery to allow for pre-processing the jade source
     jade_loader = Loader(
         ('django.template.loaders.filesystem.Loader',))
     tmpl_src, display_name = jade_loader.load_template_source(
         jade_template_path, [self.template_path,])
     if self.INCLUDE_RE.search(tmpl_src):
         tmpl_src = self.preprocess_includes(tmpl_src)
     # WHITESPACE! HUH! WHAAAAT IS IT GOOD FOR? ABSOLUTELY NOTHING!
     tmpl_src = u'\n'.join([line for line in tmpl_src.split('\n')
                            if line.strip()])
     origin = loader.make_origin(display_name,
                                 jade_loader.load_template_source,
                                 jade_template_path, None)
     if settings.DEBUG:
         logger.debug(
             u'Template is: \n%s',
             u'\n'.join(['%4d: %s' % (i, s)
                        for i, s in enumerate(tmpl_src.split('\n'))]))
     compiled_jade = process(tmpl_src, filename=jade_template_path,
                             compiler=Compiler)
     try:
         tmpl = loader.get_template_from_string(compiled_jade, origin,
                                                jade_template_path)
     except Exception, e:
         logger.exception('Failed to compile Jade-derived HTML template:')
         logger.exception(
             u'\n'.join(['%4d: %s' % (i, s)
                        for i, s in enumerate(compiled_jade.split(u'\n'))]))
         raise
Esempio n. 28
0
def convert_file():
    import codecs
    aviable_compilers = {}
    try:
        from pyjade.ext.django import Compiler as DjancoCompiler
        aviable_compilers['django'] = DjancoCompiler
    except:
        pass
    try:
        from pyjade.ext.jinja import Compiler as JinjaCompiler
        aviable_compilers['jinja'] = JinjaCompiler
    except:
        pass
    try:
        from pyjade.ext.underscore import Compiler as UnderscoreCompiler
        aviable_compilers['underscore'] = UnderscoreCompiler
    except:
        pass
    try:
        from pyjade.ext.mako import Compiler as MakoCompiler
        aviable_compilers['mako'] = MakoCompiler
    except:
        pass
    from optparse import OptionParser
    usage = "usage: %prog [options] file [output]"
    parser = OptionParser(usage)
    parser.add_option("-o",
                      "--output",
                      dest="output",
                      help="write output to FILE",
                      metavar="FILE")
    parser.add_option(
        "-c",
        "--compiler",
        dest="compiler",
        choices=[
            'django',
            'jinja',
            'mako',
            'underscore',
        ],
        default='django',
        type="choice",
        help="COMPILER must be django (default), jinja, underscore or mako ")
    # parser.add_option("-q", "--quiet",
    #                   action="store_false", dest="verbose", default=True,
    #                   help="don't print status messages to stdout")
    (options, args) = parser.parse_args()
    if len(args) < 1:
        print "Specify the input file as the first argument."
        exit()
    file_output = options.output or (args[1] if len(args) > 1 else None)
    compiler = options.compiler
    if compiler in aviable_compilers:
        template = codecs.open(args[0], 'r', encoding='utf-8').read()
        output = process(template, compiler=aviable_compilers[compiler])
        if file_output:
            outfile = codecs.open(file_output, 'w', encoding='utf-8')
            outfile.write(output)
        else:
            print output
    else:
        raise Exception('You must have %s installed!' % compiler)
Esempio n. 29
0
def preprocessor(source):
    return process(source, compiler=Compiler)
Esempio n. 30
0
 def templatize(src, origin=None):
     html = process(src,compiler=Compiler)
     return func(html, origin)
Esempio n. 31
0
def preprocessor(source):
    return process(source,compiler=Compiler)
Esempio n. 32
0
 def templatize(src, origin=None):
     src = force_text(src, settings.FILE_CHARSET)
     html = process(src, compiler=Compiler)
     return func(html, origin)
Esempio n. 33
0
def convert_file():
    support_compilers_list = [
        'django', 'jinja', 'underscore', 'mako', 'tornado', 'html'
    ]
    available_compilers = {}
    for i in support_compilers_list:
        try:
            compiler_class = __import__('pyjade.ext.%s' % i,
                                        fromlist=['pyjade']).Compiler
        except ImportError as e:
            logging.warning(e)
        else:
            available_compilers[i] = compiler_class

    usage = "usage: %prog [options] [file [output]]"
    parser = OptionParser(usage)
    parser.add_option("-o",
                      "--output",
                      dest="output",
                      help="Write output to FILE",
                      metavar="FILE")
    # use a default compiler here to sidestep making a particular
    # compiler absolutely necessary (ex. django)
    default_compiler = sorted(available_compilers.keys())[0]
    parser.add_option(
        "-c",
        "--compiler",
        dest="compiler",
        choices=list(available_compilers.keys()),
        default=default_compiler,
        type="choice",
        help=("COMPILER must be one of %s, default is %s" %
              (', '.join(list(available_compilers.keys())), default_compiler)))
    parser.add_option("-e",
                      "--ext",
                      dest="extension",
                      help="Set import/extends default file extension",
                      metavar="FILE")

    parser.add_option(
        "-r",
        "--recursive",
        action="store_true",
        dest="recursive",
        help="Converts all files in this directory and subdirectories",
        metavar="DIRECTORY")

    options, args = parser.parse_args()

    file_output = options.output or (args[1] if len(args) > 1 else None)
    compiler = options.compiler
    recursive = options.recursive

    if options.extension:
        extension = '.%s' % options.extension
    elif options.output:
        extension = os.path.splitext(options.output)[1]
    else:
        extension = None

    if compiler in available_compilers:
        import six
        # do all the conversion first if its a file ...
        if len(args) >= 1:
            print(args)
            if os.path.isfile(args[0]):  # checks if args[0] is a file.
                template = codecs.open(args[0], 'r', encoding='utf-8').read()
            elif six.PY3 and not os.path.isfile(args[0]) and not os.path.isdir(
                    args[0]
            ):  # check if any arguments or flags was specified then read from std in if there wasnt.
                template = sys.stdin.read()
            elif os.path.isdir(args[0]):
                template = False
            elif os.path.isfile(args[0]) and not codecs.open(
                    args[0], 'r', encoding='utf-8').read(
                    ):  # input is a file but cant be read.
                try:
                    template = codecs.getreader('utf-8')(sys.stdin).read()
                except Exception as e:
                    print(e)
            if template:  #usally gets here because of file or stdin was specified.
                output = process(template,
                                 compiler=available_compilers[compiler],
                                 staticAttrs=True,
                                 extension=extension)

        ### the rest of the output saves the pyjade output or does the converting now if its a folder.

        # do not call the walk directory routine if a dir is specified without the recursive ("-r") option.
        # "explicit is better than implicit" - The Zen Of Python.

        # lists all files in directories and lower subdirectories.
        # will raise "not a directory error" if user specifies a file or other.
        if recursive and os.path.isdir(args[0]):
            for root, dirs, files in os.walk(args[0], topdown=False):
                for name in files:
                    current_file_path = os.path.join(
                        root, name
                    )  # returns full file path , for example: /home/user/stuff/example.jade
                    if "*.jade" not in current_file_path:
                        # could of done it inline with the walk - but i prefer readability.
                        pass
                    template = codecs.open(current_file_path,
                                           'r',
                                           encoding='utf-8').read(
                                           )  # should only be a .jade file.

                    ### TODO - OUTPUT FILE EXTENSION VARIABLE
                    output_filepath = current_file_path[:current_file_path.rfind(
                        "."
                    )] + ".html"  # strips "jade" at the end of the path and replaces it with "html" which could be a variable in future.
                    # methods for each file in directory and all sub directories goes here.
                    output = process(template,
                                     compiler=available_compilers[compiler],
                                     staticAttrs=True,
                                     extension=extension)
                    outfile = codecs.open(output_filepath,
                                          'w',
                                          encoding='utf-8')
                    outfile.write(output)

        # len(args) >= 1 added for debuging success conformation
        elif len(args) >= 1 and os.path.isdir(
                args[0]
        ):  # if path specified is a directory and has no -r option specified, then make sure the user wanted to do this.
            raise Exception(
                "%s is a directory. \n Please use the '-r' flag if you want to convert a directory and all its subdirectories "
                % (args[0]))
        # len(args) >= 1 added for debuging success conformation
        elif len(args) >= 1 and os.path.isfile(
                args[0]
        ):  # if it gets to here without ending, then a single file or multiple explicit files were specified.
            # single file operations
            if file_output:  # will raise Exception "is not file" if its a directory or other - no really! inheritance!
                outfile = codecs.open(file_output, 'w', encoding='utf-8')
                outfile.write(output)
            elif six.PY3:
                sys.stdout.write(output)
            else:
                codecs.getwriter('utf-8')(sys.stdout).write(output)

    else:
        raise Exception('You must have %s installed!' % compiler)
Esempio n. 34
0
def convert_file():
    support_compilers_list = ['django', 'jinja', 'underscore', 'mako', 'tornado', 'html']
    available_compilers = {}
    for i in support_compilers_list:
        try:
            if i == "django":
                from django.conf import settings
                settings.configure()

            compiler_class = __import__('pyjade.ext.%s' % i, fromlist=['pyjade']).Compiler
        except ImportError as e:
            logging.warning(e)
        else:
            available_compilers[i] = compiler_class

    usage = "usage: %(prog)s [options] [input [output]]"
    parser = argparse.ArgumentParser(usage=usage)

    parser.add_argument("-o", "--output", help="write output to FILE", metavar="FILE")

    # use a default compiler here to sidestep making a particular
    # compiler absolutely necessary (ex. django)
    default_compiler = sorted(available_compilers.keys())[0]
    parser.add_argument("-c", "--compiler",
                    choices=list(available_compilers.keys()),
                    default=default_compiler,
                    metavar="COMPILER",
                    help="template compiler, %s by default; supported compilers are: %s" % (default_compiler, ", ".join(available_compilers.keys())))
    parser.add_argument("-e", "--ext", dest="extension",
                      help="set import/extends default file extension",
                      metavar="FILE")
    parser.add_argument("--block_start_string", metavar="STRING", default="{%", help="valid for jinja compiler only, defaut is '{%%'")
    parser.add_argument("--block_end_string", metavar="STRING", default="%}", help="valid for jinja compiler only, defaut is '%%}'")
    parser.add_argument("--variable_start_string", metavar="STRING", default="{{", help="valid for jinja compiler only, defaut is '{{'")
    parser.add_argument("--variable_end_string", metavar="STRING", default="}}", help="valid for jinja compiler only, defaut is '}}'")
    parser.add_argument("input", nargs="?")
    parser.add_argument("output", nargs="?", default=argparse.SUPPRESS)

    args = parser.parse_args()

    compiler = args.compiler

    if args.extension:
        extension = '.%s' % args.extension
    elif args.output:
        extension = os.path.splitext(args.output)[1]
    else:
        extension = None

    if compiler in available_compilers:
        import six
        if args.input:
            template = codecs.open(args.input, 'r', encoding='utf-8').read()
        elif six.PY3:
            template = sys.stdin.read()
        else:
            template = codecs.getreader('utf-8')(sys.stdin).read()

        output = process(template, compiler=available_compilers[compiler],
                         staticAttrs=True, extension=extension,
                         block_start_string=args.block_start_string,
                         block_end_string=args.block_end_string,
                         variable_start_string=args.variable_start_string,
                         variable_end_string=args.variable_end_string)

        if args.output:
            outfile = codecs.open(args.output, 'w', encoding='utf-8')
            outfile.write(output)
        elif six.PY3:
            sys.stdout.write(output)
        else:
            codecs.getwriter('utf-8')(sys.stdout).write(output)
    else:
        raise Exception('You must have %s installed!' % compiler)
Esempio n. 35
0
 def preprocess(self, source, name, filename=None):
     return process(source,
                    filename=name,
                    compiler=JinjaAutoescapeCompiler,
                    **self.options)
Esempio n. 36
0
 def process_jade(self, source, template_name):
     return process(source,
                    filename=template_name,
                    parser=Parser,
                    compiler=Compiler,
                    doctype='5')
Esempio n. 37
0
def convert_file():
    support_compilers_list = [
        'django', 'jinja', 'underscore', 'mako', 'tornado', 'html'
    ]
    available_compilers = {}
    for i in support_compilers_list:
        try:
            if i == "django":
                from django.conf import settings
                settings.configure()

            compiler_class = __import__('pyjade.ext.%s' % i,
                                        fromlist=['pyjade']).Compiler
        except ImportError as e:
            logging.warning(e)
        else:
            available_compilers[i] = compiler_class

    usage = "usage: %(prog)s [options] [input [output]]"
    parser = argparse.ArgumentParser(usage=usage)

    parser.add_argument("-o",
                        "--output",
                        help="write output to FILE",
                        metavar="FILE")

    # use a default compiler here to sidestep making a particular
    # compiler absolutely necessary (ex. django)
    default_compiler = sorted(available_compilers.keys())[0]
    parser.add_argument(
        "-c",
        "--compiler",
        choices=list(available_compilers.keys()),
        default=default_compiler,
        metavar="COMPILER",
        help="template compiler, %s by default; supported compilers are: %s" %
        (default_compiler, ", ".join(available_compilers.keys())))
    parser.add_argument("-e",
                        "--ext",
                        dest="extension",
                        help="set import/extends default file extension",
                        metavar="FILE")
    parser.add_argument("--block_start_string",
                        metavar="STRING",
                        default="{%",
                        help="valid for jinja compiler only, defaut is '{%%'")
    parser.add_argument("--block_end_string",
                        metavar="STRING",
                        default="%}",
                        help="valid for jinja compiler only, defaut is '%%}'")
    parser.add_argument("--variable_start_string",
                        metavar="STRING",
                        default="{{",
                        help="valid for jinja compiler only, defaut is '{{'")
    parser.add_argument("--variable_end_string",
                        metavar="STRING",
                        default="}}",
                        help="valid for jinja compiler only, defaut is '}}'")
    parser.add_argument("input", nargs="?")
    parser.add_argument("output", nargs="?", default=argparse.SUPPRESS)

    args = parser.parse_args()

    compiler = args.compiler

    if args.extension:
        extension = '.%s' % args.extension
    elif args.output:
        extension = os.path.splitext(args.output)[1]
    else:
        extension = None

    if compiler in available_compilers:
        import six
        if args.input:
            template = codecs.open(args.input, 'r', encoding='utf-8').read()
        elif six.PY3:
            template = sys.stdin.read()
        else:
            template = codecs.getreader('utf-8')(sys.stdin).read()

        output = process(template,
                         compiler=available_compilers[compiler],
                         staticAttrs=True,
                         extension=extension,
                         block_start_string=args.block_start_string,
                         block_end_string=args.block_end_string,
                         variable_start_string=args.variable_start_string,
                         variable_end_string=args.variable_end_string)

        if args.output:
            outfile = codecs.open(args.output, 'w', encoding='utf-8')
            outfile.write(output)
        elif six.PY3:
            sys.stdout.write(output)
        else:
            codecs.getwriter('utf-8')(sys.stdout).write(output)
    else:
        raise Exception('You must have %s installed!' % compiler)
Esempio n. 38
0
 def preprocess(self, source, name, filename=None):
     if name and not os.path.splitext(name)[1] in self.file_extensions:
         return source
     return process(source,filename=name,compiler=Compiler,**self.options)
Esempio n. 39
0
 def _compiler(s):
     return process(s, compiler=template_compiler, staticAttrs=True, extension='.html')
Esempio n. 40
0
 def templatize(src, origin=None):
     src = to_text(src, settings.FILE_CHARSET)
     html = process(src, compiler=Compiler)
     return func(html, origin)
Esempio n. 41
0
 def as_html(self):
     return process(self.template)
Esempio n. 42
0
def preprocessor(source):
    # if name and not os.path.splitext(name)[1] in self.environment.jade_file_extensions:
    #     return source
    return process(source, compiler=Compiler)
Esempio n. 43
0
    parser.add_option("-e", "--ext", dest="extension",
                    help="Set import/extends default file extension", metavar="FILE")

    options, args = parser.parse_args()
    if len(args) < 1:
        print "Specify the input file as the first argument."
        exit()
    file_output = options.output or (args[1] if len(args) > 1 else None)
    compiler = options.compiler

    if options.extension:
        extension = '.%s'%options.extension
    elif options.output:
        extension = os.path.splitext(options.output)[1]
    else:
        extension = None

    if compiler in available_compilers:
        template = codecs.open(args[0], 'r', encoding='utf-8').read()
        output = process(template, compiler=available_compilers[compiler], staticAttrs=True, extension=extension)
        if file_output:
            outfile = codecs.open(file_output, 'w', encoding='utf-8')
            outfile.write(output)
        else:
            print output
    else:
        raise Exception('You must have %s installed!' % compiler)

if __name__ == '__main__':
    convert_file()
Esempio n. 44
0
 def preprocess(self, source, name, filename=None):
     if name and not os.path.splitext(name)[1] in self.environment.jade_file_extensions:
         return source
     return process(source,filename=name,compiler=Compiler)
Esempio n. 45
0
processors['Html'] = pyjade.ext.html.process_jade


def run_case(case, process):
    global processors
    process = processors[process]
    jade_file = open('cases/%s.jade' % case)
    jade_src = jade_file.read().decode('utf-8')
    jade_file.close()

    html_file = open('cases/%s.html' % case)
    html_src = html_file.read().strip('\n').decode('utf-8')
    html_file.close()
    try:
        processed_jade = process(jade_src).strip('\n')
        print 'PROCESSED\n', processed_jade, len(processed_jade)
        print 'EXPECTED\n', html_src, len(html_src)
        assert processed_jade == html_src
    except CurrentlyNotSupported:
        pass


exclusions = {
    'Html': set(['mixins', 'layout', 'unicode']),
    'Mako': set(['layout']),
    'Jinja2': set(['layout']),
    'Django': set(['layout'])
}

Esempio n. 46
0
File: jade.py Progetto: mardix/Mocha
def convert(text, filename=None):
    return process(text, filename=filename, compiler=Compiler)
Esempio n. 47
0
 def preprocess(self, source, name, filename=None):
     if (not name or
             (name and not os.path.splitext(name)[1] in self.file_extensions)):
         return source
     return process(source, filename=name, compiler=JinjaAutoescapeCompiler, **self.options)
Esempio n. 48
0
 def templatize(src, origin=None):
     html = process(src,compiler=Compiler)
     return func(html, origin)
Esempio n. 49
0
def convert_file():
    support_compilers_list = ['django', 'jinja', 'underscore', 'mako', 'tornado', 'html']
    available_compilers = {}
    for i in support_compilers_list:
        try:
            compiler_class = __import__('pyjade.ext.%s' % i, fromlist=['pyjade']).Compiler
        except ImportError as e:
            logging.warning(e)
        else:
            available_compilers[i] = compiler_class

    usage = "usage: %prog [options] [file [output]]"
    parser = OptionParser(usage)
    parser.add_option("-o", "--output", dest="output",
                    help="Write output to FILE", metavar="FILE")
    # use a default compiler here to sidestep making a particular
    # compiler absolutely necessary (ex. django)
    default_compiler = sorted(available_compilers.keys())[0]
    parser.add_option("-c", "--compiler", dest="compiler",
                    choices=list(available_compilers.keys()),
                    default=default_compiler,
                    type="choice",
                    help=("COMPILER must be one of %s, default is %s" %
                          (', '.join(list(available_compilers.keys())), default_compiler)))
    parser.add_option("-e", "--ext", dest="extension",
                      help="Set import/extends default file extension",
                      metavar="FILE")

    parser.add_option("-r", "--recursive", action="store_true", dest="recursive",
                      help="Converts all files in this directory and subdirectories",metavar="DIRECTORY")

    options, args = parser.parse_args()

    file_output = options.output or (args[1] if len(args) > 1 else None)
    compiler = options.compiler
    recursive = options.recursive

    if options.extension:
        extension = '.%s' % options.extension
    elif options.output:
        extension = os.path.splitext(options.output)[1]
    else:
        extension = None

    if compiler in available_compilers:
        import six
        # do all the conversion first if its a file ...
        if len(args) >= 1:
            print(args)
            if os.path.isfile(args[0]): # checks if args[0] is a file.
                template = codecs.open(args[0], 'r', encoding='utf-8').read()
            elif six.PY3 and not os.path.isfile(args[0]) and not os.path.isdir(args[0]) :  # check if any arguments or flags was specified then read from std in if there wasnt.
                template = sys.stdin.read()
            elif os.path.isdir(args[0]):
                template = False
            elif os.path.isfile(args[0]) and not codecs.open(args[0], 'r', encoding='utf-8').read() : # input is a file but cant be read.
                try:
                    template = codecs.getreader('utf-8')(sys.stdin).read()
                except Exception as e:
                    print(e)
            if template: #usally gets here because of file or stdin was specified.
                output = process(template, compiler=available_compilers[compiler],staticAttrs=True, extension=extension)

        ### the rest of the output saves the pyjade output or does the converting now if its a folder.

        # do not call the walk directory routine if a dir is specified without the recursive ("-r") option.
        # "explicit is better than implicit" - The Zen Of Python.

        # lists all files in directories and lower subdirectories.
        # will raise "not a directory error" if user specifies a file or other.
        if recursive and os.path.isdir(args[0]):
            for root, dirs, files in os.walk(args[0], topdown=False):
                for name in files:
                    current_file_path = os.path.join(root, name) # returns full file path , for example: /home/user/stuff/example.jade
                    if "*.jade" not in current_file_path:
                    # could of done it inline with the walk - but i prefer readability.
                        pass
                    template = codecs.open(current_file_path, 'r', encoding='utf-8').read() # should only be a .jade file.

                    ### TODO - OUTPUT FILE EXTENSION VARIABLE
                    output_filepath = current_file_path[:current_file_path.rfind(".")] + ".html" # strips "jade" at the end of the path and replaces it with "html" which could be a variable in future.
                    # methods for each file in directory and all sub directories goes here.
                    output = process(template, compiler=available_compilers[compiler], staticAttrs=True, extension=extension)
                    outfile = codecs.open(output_filepath, 'w', encoding='utf-8')
                    outfile.write(output)

        # len(args) >= 1 added for debuging success conformation
        elif len(args) >= 1 and os.path.isdir(args[0]): # if path specified is a directory and has no -r option specified, then make sure the user wanted to do this.
            raise Exception("%s is a directory. \n Please use the '-r' flag if you want to convert a directory and all its subdirectories " % (args[0]))
        # len(args) >= 1 added for debuging success conformation
        elif len(args) >= 1 and os.path.isfile(args[0]): # if it gets to here without ending, then a single file or multiple explicit files were specified.
            # single file operations
            if file_output:  # will raise Exception "is not file" if its a directory or other - no really! inheritance!
                outfile = codecs.open(file_output, 'w', encoding='utf-8')
                outfile.write(output)
            elif six.PY3:
                sys.stdout.write(output)
            else:
                codecs.getwriter('utf-8')(sys.stdout).write(output)


    else:
        raise Exception('You must have %s installed!' % compiler)