def template(path, extend_path, out):
    """
    Return a jinja2 template instance with extends support.
    """
    files = []

    # add the "extender" template when it exists
    if len(extend_path) > 0:
        # determine the base readme path
        base_path = os.path.dirname(extend_path)
        new_base_path = os.path.join(base_path, "README.{0}.j2".format(out))

        if os.path.exists(new_base_path):
            path = new_base_path

        if os.path.exists(extend_path):
            files = [path, extend_path]
        else:
            ui.error(c.MESSAGES["template_extender_missing"])
            ui.error(extend_path)
            sys.exit(1)
    else:
        files = [path]

    try:
        # Use the subclassed relative environment class
        env = RelEnvironment(trim_blocks=True)

        # Add a unique dict filter, by key.
        # DEPRECATION WARNING: This is only used for backwards compatibility,
        #                      please use the unique filter instead.
        def unique_dict(items, key):
            return {v[key]: v for v in items}.values()

        env.filters["unique_dict"] = unique_dict

        def unique(a):

            # Don’t use the following commented out optimization which is used
            # in ansible/lib/ansible/plugins/filter/mathstuff.py in Ansigenome
            # as it resorts the role dependencies:
            # if isinstance(a,collections.Hashable):
            #     c = set(a)

            c = []
            for x in a:
                if x not in c:
                    c.append(x)
            return c

        env.filters["unique"] = unique

        # create a dictionary of templates
        templates = dict(
            (name, codecs.open(name, "rb", 'UTF-8').read())
            for name in files)
        env.loader = DictLoader(templates)

        # return the final result (the last template in the list)
        return env.get_template(files[len(files) - 1])
    except Exception as err:
        ui.error(c.MESSAGES["template_error"], err)
        sys.exit(1)
Return a jinja2 template instance with extends support.