Python jinja2 模块,PrefixLoader() 实例源码

我们从Python开源项目中,提取了以下2个代码示例,用于说明如何使用jinja2.PrefixLoader()

项目:inmanta    作者:inmanta    | 项目源码 | 文件源码
def _get_template_engine(ctx):
    """
        Initialize the template engine environment
    """
    global engine_cache
    if engine_cache is not None:
        return engine_cache

    loader_map = {}
    loader_map[""] = FileSystemLoader(os.path.join(Project.get().project_path, "templates"))
    for name, module in Project.get().modules.items():
        template_dir = os.path.join(module._path, "templates")
        if os.path.isdir(template_dir):
            loader_map[name] = FileSystemLoader(template_dir)

    # init the environment
    env = Environment(loader=PrefixLoader(loader_map), undefined=jinja2.StrictUndefined)
    env.context_class = ResolverContext

    # register all plugins as filters
    for name, cls in ctx.get_compiler().get_plugins().items():
        def curywrapper(func):
            def safewrapper(*args):
                return JinjaDynamicProxy.return_value(func(*args))
            return safewrapper
        env.filters[name.replace("::", ".")] = curywrapper(cls)

    engine_cache = env
    return env
项目:Mocha    作者:mardix    | 项目源码 | 文件源码
def register_package(pkg, prefix=None):
    """
    Allow to register an app packages by loading and exposing: templates, static,
    and exceptions for abort()

    Structure of package
        root
            | $package_name
                | __init__.py
                |
                | /templates
                    |
                    |
                |
                | /static
                    |
                    | assets.yml

    :param pkg: str - __package__
                    or __name__
                    or The root dir
                    or the dotted resource package (package.path.path,
                    usually __name__ of templates and static
    :param prefix: str - to prefix the template path
    """

    root_pkg_dir = pkg
    if not os.path.isdir(pkg) and "." in pkg:
        root_pkg_dir = pkg_resources.resource_filename(pkg, "")

    template_path = os.path.join(root_pkg_dir, "templates")
    static_path = os.path.join(root_pkg_dir, "static")

    logging.info("Registering App: " + pkg)
    if os.path.isdir(template_path):
        loader = jinja2.FileSystemLoader(template_path)
        if prefix:
            ploader = jinja2.PrefixLoader({
                prefix: loader
            })
            loader = ploader
        Mocha._template_paths.add(loader)

    if os.path.isdir(static_path):
        Mocha._static_paths.add(static_path)
        Mocha._add_asset_bundle(static_path)