template.py 文件源码

python
阅读 31 收藏 0 点赞 0 评论 0

项目:py-script 作者: xiaoxiamin 项目源码 文件源码
def compile_templates(root):
    """Compiles templates to python code."""
    re_start = re_compile('^', re.M)

    for dirpath, dirnames, filenames in os.walk(root):
        filenames = [f for f in filenames if not f.startswith('.') and not f.endswith('~') and not f.startswith('__init__.py')]

        for d in dirnames[:]:
            if d.startswith('.'):
                dirnames.remove(d) # don't visit this dir

        out = open(os.path.join(dirpath, '__init__.py'), 'w')
        out.write('from web.template import CompiledTemplate, ForLoop, TemplateResult\n\n')
        if dirnames:
            out.write("import " + ", ".join(dirnames))
        out.write("\n")

        for f in filenames:
            path = os.path.join(dirpath, f)

            if '.' in f:
                name, _ = f.split('.', 1)
            else:
                name = f

            text = open(path).read()
            text = Template.normalize_text(text)
            code = Template.generate_code(text, path)

            code = code.replace("__template__", name, 1)

            out.write(code)

            out.write('\n\n')
            out.write('%s = CompiledTemplate(%s, %s)\n' % (name, name, repr(path)))
            out.write("join_ = %s._join; escape_ = %s._escape\n\n" % (name, name))

            # create template to make sure it compiles
            t = Template(open(path).read(), path)
        out.close()
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号