Ejemplo n.º 1
0
    def test_searchpath_as_pathlib(self):
        import pathlib

        searchpath = pathlib.Path(self.searchpath)
        filesystem_loader = loaders.FileSystemLoader(searchpath)
        env = Environment(loader=filesystem_loader)
        self._test_common(env)
Ejemplo n.º 2
0
    def ready(self):
        global JINJA_RENDERER
        jinja_env = jinja2.Environment(
            loader=loaders.FileSystemLoader(TEMPALTES_PATH),
            trim_blocks=True,
            lstrip_blocks=True,
            extensions=['jinja2.ext.do'])
        JINJA_RENDERER = jinja2py.JinjaRenderer(jinja_env)

        generate_names = list()
        codes = dict()
        for f in os.listdir(TEMPALTES_PATH):
            if f in BANED_NAMES:
                continue
            if os.path.isfile(os.path.join(TEMPALTES_PATH, f)):
                if f.endswith('.py.jinja2'):
                    generate_names.append(f[:-len('.jinja2')])
                elif f.endswith('.py'):
                    with open(os.path.join(TEMPALTES_PATH, f)) as c:
                        codes[f] = c.read()

        global GENERATE_NAMES
        GENERATE_NAMES = generate_names
        global CODES
        CODES = codes
Ejemplo n.º 3
0
 def test_filename_normpath(self):
     """Nested template names should only contain ``os.sep`` in the
     loaded filename.
     """
     loader = loaders.FileSystemLoader(self.searchpath)
     e = Environment(loader=loader)
     t = e.get_template("foo/test.html")
     assert t.filename == str(self.searchpath / "foo" / "test.html")
Ejemplo n.º 4
0
def filesystem_loader():
    """returns FileSystemLoader initialized to res/templates directory"""
    try:
        import yatest.common
        here = yatest.common.test_source_path()
    except ImportError:
        here = os.path.dirname(os.path.abspath(__file__))
    return loaders.FileSystemLoader(here + "/res/templates")
Ejemplo n.º 5
0
    def test_searchpath_as_list_including_pathlib(self):
        import pathlib

        searchpath = pathlib.Path(self.searchpath)
        filesystem_loader = loaders.FileSystemLoader(
            ["/tmp/templates", searchpath])
        env = Environment(loader=filesystem_loader)
        self._test_common(env)
Ejemplo n.º 6
0
def _make_jinja_app_loader():
    """Makes an 'app loader' for Jinja which acts like
    :mod:`django.template.loaders.app_directories`.
    """
    from django.template.loaders.app_directories import app_template_dirs
    loader = loaders.FileSystemLoader([])
    loader.searchpath = GetTemplateDirs(lambda: app_template_dirs)
    return loader
Ejemplo n.º 7
0
def _make_jinja_filesystem_loader():
    """Makes a 'filesystem loader' for Jinja which acts like
    :mod:`django.template.loaders.filesystem`.
    """
    from django.conf import settings
    loader = loaders.FileSystemLoader([])
    loader.searchpath = GetTemplateDirs(lambda: settings.TEMPLATE_DIRS)
    return loader
Ejemplo n.º 8
0
 def test_filesystem_loader_searchpaths(self):
     pathlib = pytest.importorskip('pathlib')
     here = os.path.dirname(os.path.abspath(__file__))
     tmpl_path = os.path.join(here, 'res', 'templates', 'foo')
     for p in [tmpl_path, pathlib.Path(tmpl_path)]:
         loader = loaders.FileSystemLoader(p)
         env = Environment(loader=loader)
         tmpl = env.get_template('test.html')
         assert tmpl.render().strip() == 'FOO'
Ejemplo n.º 9
0
 def _get_loaders(self):
     """this method is not used
     over-ridden function _get_loaders that creates
     the loader for the skin templates
     """
     loaders = list()
     skin_dirs = utils.get_available_skins(selected=self.skin).values()
     template_dirs = [os.path.join(skin_dir, 'templates') for skin_dir in skin_dirs]
     loaders.append(jinja_loaders.FileSystemLoader(template_dirs))
     return loaders
Ejemplo n.º 10
0
    def test_caches_template_based_on_mtime(self):
        filesystem_loader = loaders.FileSystemLoader(self.searchpath)

        env = Environment(loader=filesystem_loader)
        tmpl1 = env.get_template("test.html")
        tmpl2 = env.get_template("test.html")
        assert tmpl1 is tmpl2

        os.utime(self.searchpath / "test.html", (time.time(), time.time()))
        tmpl3 = env.get_template("test.html")
        assert tmpl1 is not tmpl3
Ejemplo n.º 11
0
    def __init__(self, packages):
        self.searchpath = ['templates']
        try:
            self.fsl = loaders.FileSystemLoader(self.searchpath)
        except Exception as e:
            log.error(e)

        self.modules = packages
        self.packages = {}
        self.encoding = 'utf-8'
        self.package_path = "templates"
        self.manager = ResourceManager()
Ejemplo n.º 12
0
def filesystem_loader():
    '''returns FileSystemLoader initialized to res/templates directory
    '''
    here = os.path.dirname(os.path.abspath(__file__))
    return loaders.FileSystemLoader(here + '/res/templates')
Ejemplo n.º 13
0
 def test_uses_specified_encoding(self, encoding, expect):
     loader = loaders.FileSystemLoader(self.searchpath, encoding=encoding)
     e = Environment(loader=loader)
     t = e.get_template("mojibake.txt")
     assert t.render() == expect
Ejemplo n.º 14
0
    def test_searchpath_as_str(self):
        filesystem_loader = loaders.FileSystemLoader(str(self.searchpath))

        env = Environment(loader=filesystem_loader)
        self._test_common(env)
Ejemplo n.º 15
0
def main():

    # Parse anli dir, data persistence.
    dic = _parse_dir()
    _create_db(dic)

    # Read data from database
    anli_table = _read_db()

    # Hold data needed to be rendered in one list.
    html_result = []

    # Create index.html template render data.
    # {
    #   "html_title": "",
    #   "xiaotu_dict": {
    #     "keji": {
    #       "name": "KEJI",
    #       "list": [
    #         ("cx_keji_01_1_shouyexiaotu1", 1),
    #         ("cx_keji_02_1_shouyexiaotu2", 2)
    #       ]
    #     }
    #   },
    #   "datu_list": [
    #     ("cx_keji_01_1_shouyedatu1", 1),
    #     ("cx_keji_02_1_shouyedatu2", 2)
    #   ],
    #   "meta": {}
    # }
    xiaotu_dict = {}
    datu_list = []

    for anli in anli_table:
        anli_dir_name = anli["id"]
        if "shouyexiaotu_order" in anli:
            order = anli["shouyexiaotu_order"]
            anli_name = anli["mingcheng"]
            fengge_key = _get_fengge_key(anli_dir_name)

            # Create empty list when not exist.
            if fengge_key not in xiaotu_dict:
                xiaotu_dict[fengge_key] = {}
                xiaotu_dict[fengge_key]["name"] = anli["fengge_name"]
                xiaotu_dict[fengge_key]["list"] = []

            fengge = xiaotu_dict[fengge_key]
            fengge["list"].append((anli_dir_name, anli_name, order))

            # Sort with order number
            fengge["list"] = sorted(fengge["list"], key=lambda anli: anli[2])

        if "shouyedatu_order" in anli:
            order = anli["shouyedatu_order"]
            datu_list.append((anli_dir_name, order - 1))
            # Sort with order number
            datu_list = sorted(datu_list, key=lambda anli: anli[1])

    html_result.append({
        "file_name": "index.html",
        "template_name": "anlizhanshi/index.html",
        "render_data": {
            "html_title": u"3D展厅模板 - 首页",
            "fengge_dict": xiaotu_dict,
            "datu_list": datu_list,
            "meta": META
        }
    })

    # Create more.html template render data.
    # {
    #   "html_title": "",
    #   "fengge_name": "",
    #   "item_list": {
    #     "name": "KEJI",
    #     "list": [
    #       ("cx_keji_01_1", "cx_keji_01_1", 1452661512, "2016-01-13T05:05:12+00:00"),
    #       ("cx_keji_02_1", "科技案例02", 1452661512, "2016-01-13T05:05:12+00:00")
    #     ]
    #   },
    #   "count": 45,
    #   "option": {
    #     "limit": 20
    #   },
    #   "meta": {}
    # }

    for fengge_key in _db_group("fengge_key", anli_table):
        anli_list = _db_select("fengge_key", fengge_key, anli_table)
        anli_count = len(anli_list)
        page_number = 1
        current_page_list = []
        current_anli_index = 1
        for anli in anli_list:
            anli_dir_name = anli[0]
            anli_name = anli[1]
            fengge_name = _get_fengge_name(anli_dir_name)

            dir_created_unix_time = _get_created_date(anli_dir_name)  # int
            dir_created_time = time.ctime(dir_created_unix_time)

            current_page_list.append(
                # dir_name      # dir_created_date
                (anli_dir_name, anli_name, dir_created_unix_time,
                 str(dir_created_time)))

            if current_anli_index % LIMIT == 0 or current_anli_index == anli_count:
                file_name = "more-" + fengge_key + "-" + str(
                    page_number) + ".html"
                html_result.append({
                    "file_name": file_name,
                    "template_name": "anlizhanshi/more.html",
                    "render_data": {
                        "html_title": u"3D展厅模板 - " + fengge_name,
                        "fengge_name": fengge_name,
                        "item_list": current_page_list,
                        "fengge_key": fengge_key,
                        "current_page": page_number,
                        "count": anli_count,
                        "option": {
                            "limit": LIMIT
                        },
                        "meta": META
                    }
                })
                current_page_list = []
                page_number += 1

            current_anli_index += 1

    #env = Environment(loader=filesystem_loader)
    env = Environment(loader=loaders.FileSystemLoader(_get_template_path()))

    for html_file in html_result:
        tmpl = env.get_template(html_file["template_name"])
        html_path = os.path.join(_get_output_path(), html_file["file_name"])
        output = tmpl.render(data=html_file["render_data"]).encode('utf8')
        with open(html_path, "wb") as fh:
            fh.write(output)
Ejemplo n.º 16
0
 def _get_loaders(self):
     template_dirs = self.get_all_template_dirs()
     return [jinja_loaders.FileSystemLoader(template_dirs)]
Ejemplo n.º 17
0
def _make_jinja_filesystem_loader():
    """Makes a 'filesystem loader' for Jinja which acts like
    :mod:`django.template.loaders.filesystem`.
    """
    from django.conf import settings
    return loaders.FileSystemLoader(settings.TEMPLATE_DIRS)
Ejemplo n.º 18
0
def _make_jinja_app_loader():
    """Makes an 'app loader' for Jinja which acts like
    :mod:`django.template.loaders.app_directories`.
    """
    from django.template.loaders.app_directories import app_template_dirs
    return loaders.FileSystemLoader(app_template_dirs)
Ejemplo n.º 19
0
def file_loader(here):
    return loaders.FileSystemLoader(os.path.join(here, 'templates'))
Ejemplo n.º 20
0
 def test_uses_specified_encoding(self, encoding, expected_text):
     filesystem_loader = loaders.FileSystemLoader(self.searchpath,
                                                  encoding=encoding)
     env = Environment(loader=filesystem_loader)
     tmpl = env.get_template('variable_encoding.txt')
     assert tmpl.render().strip() == expected_text
Ejemplo n.º 21
0
    :license: BSD, see LICENSE for more details.
"""

from py.test import raises
import time
import tempfile
from jinja2 import Environment, loaders
from jinja2.loaders import split_template_path
from jinja2.exceptions import TemplateNotFound


dict_loader = loaders.DictLoader({
    'justdict.html':        'FOO'
})
package_loader = loaders.PackageLoader('loaderres', 'templates')
filesystem_loader = loaders.FileSystemLoader('loaderres/templates')
function_loader = loaders.FunctionLoader({'justfunction.html': 'FOO'}.get)
choice_loader = loaders.ChoiceLoader([dict_loader, package_loader])
prefix_loader = loaders.PrefixLoader({
    'a':        filesystem_loader,
    'b':        dict_loader
})


def test_dict_loader():
    env = Environment(loader=dict_loader)
    tmpl = env.get_template('justdict.html')
    assert tmpl.render().strip() == 'FOO'
    raises(TemplateNotFound, env.get_template, 'missing.html')

Ejemplo n.º 22
0
def filesystem_loader():
    """returns FileSystemLoader initialized to res/templates directory"""
    here = Path(__file__).parent.resolve()
    return loaders.FileSystemLoader(here / "res" / "templates")
Ejemplo n.º 23
0
def filesystem_loader():
    """returns FileSystemLoader initialized to res/templates directory"""
    import yatest.common
    here = Path(yatest.common.test_source_path())
    return loaders.FileSystemLoader(here / "res" / "templates")
    :copyright: (c) 2010 by the Jinja Team.
    :license: BSD, see LICENSE for more details.
"""
import os
import re
import sys
import unittest
from traceback import format_exception
from jinja2 import loaders
from jinja2._compat import PY2

here = os.path.dirname(os.path.abspath(__file__))

dict_loader = loaders.DictLoader({'justdict.html': 'FOO'})
package_loader = loaders.PackageLoader('jinja2.testsuite.res', 'templates')
filesystem_loader = loaders.FileSystemLoader(here + '/res/templates')
function_loader = loaders.FunctionLoader({'justfunction.html': 'FOO'}.get)
choice_loader = loaders.ChoiceLoader([dict_loader, package_loader])
prefix_loader = loaders.PrefixLoader({
    'a': filesystem_loader,
    'b': dict_loader
})


class JinjaTestCase(unittest.TestCase):

    ### use only these methods for testing.  If you need standard
    ### unittest method, wrap them!

    def setup(self):
        pass
Ejemplo n.º 25
0
def build_loader(paths, packages):
    fs_loaders = [loaders.FileSystemLoader(path) for path in paths]

    package_loaders = [loaders.PackageLoader(package.package_name, package.template_path)
                       for package in packages]
    return loaders.ChoiceLoader(fs_loaders + package_loaders)