Mercurial > piecrust2
comparison piecrust/themes/base.py @ 709:4285b2c9b872
themes: Add support for loading from a library of themes.
author | Ludovic Chabant <ludovic@chabant.com> |
---|---|
date | Thu, 19 May 2016 22:11:27 -0700 |
parents | |
children | 0b4eb0e37363 |
comparison
equal
deleted
inserted
replaced
708:d3a5a086e5cd | 709:4285b2c9b872 |
---|---|
1 import sys | |
2 import os.path | |
3 import yaml | |
4 from piecrust import CONFIG_PATH, THEME_DIR, THEMES_DIR | |
5 | |
6 | |
7 class Theme(object): | |
8 def getPath(self): | |
9 mod_name = type(self).__module__ | |
10 mod_file = sys.modules[mod_name].__file__ | |
11 return os.path.dirname(mod_file) | |
12 | |
13 | |
14 class ThemeNotFoundError(Exception): | |
15 pass | |
16 | |
17 | |
18 class ThemeLoader(object): | |
19 def __init__(self, root_dir): | |
20 self.root_dir = root_dir | |
21 | |
22 def getThemeDir(self): | |
23 # Pre-load the config quickly to see if we're loading a specific | |
24 # theme from somehwere. | |
25 # TODO: make configs and themes load together to speed this up. | |
26 config_path = os.path.join(self.root_dir, CONFIG_PATH) | |
27 with open(config_path, 'r', encoding='utf8') as fp: | |
28 config = yaml.load(fp.read()) | |
29 site_config = config.get('site', {}) | |
30 theme = site_config.get('theme', None) | |
31 if theme is None: | |
32 return None | |
33 | |
34 # Get the list of directories in which themes are installed. | |
35 dirs = [] | |
36 themes_dirs = site_config.get('themes_dirs', []) | |
37 if isinstance(themes_dirs, str): | |
38 dirs.append(os.path.join(self.root_dir, themes_dirs)) | |
39 else: | |
40 dirs += [os.path.join(self.root_dir, p) for p in themes_dirs] | |
41 | |
42 # Add the default `themes` directory. | |
43 default_themes_dir = os.path.join(self.root_dir, THEMES_DIR) | |
44 if os.path.isdir(default_themes_dir): | |
45 dirs.append(default_themes_dir) | |
46 | |
47 # Try to find the theme the user wants. | |
48 for d in dirs: | |
49 theme_dir = os.path.join(d, theme) | |
50 if os.path.isdir(theme_dir): | |
51 return theme_dir | |
52 | |
53 raise ThemeNotFoundError( | |
54 "Can't find theme '%s'. Looked in: %s", | |
55 (theme, ', '.join(dirs))) | |
56 |