95 lines
3.2 KiB
Python
95 lines
3.2 KiB
Python
from flask_flatpages import FlatPages, pygments_style_defs
|
|
import flask_flatpages
|
|
import re
|
|
from utils import path_depth,pjoin2
|
|
from collections import namedtuple
|
|
|
|
FileLists=namedtuple("FileLists", ["list_files", "list_images", "sub_pages", "sub_index_pages", "breadcrumbs"])
|
|
|
|
class FlatPagesIndex(FlatPages):
|
|
@staticmethod
|
|
def get_breadcrumb_paths(path):
|
|
"""
|
|
breadcrumbs decompose the path
|
|
a/b/index -> [a/index a/b/index]
|
|
"""
|
|
elements = path.split('/')
|
|
elements2 = ['index']
|
|
for i in range(1,len(elements)):
|
|
elements2.append(pjoin2(elements[0:i])+u'/index')
|
|
return elements2
|
|
|
|
|
|
@staticmethod
|
|
def get_paths(pages):
|
|
return (p.path for p in pages)
|
|
|
|
@staticmethod
|
|
def breadcrumbs(page):
|
|
"Parse a path or the path of a page into breadcrumbs"
|
|
if type(page) is flask_flatpages.Page:
|
|
return FlatPagesIndex.get_breadcrumb_paths(page.path)
|
|
else:
|
|
return FlatPagesIndex.get_breadcrumb_paths(page)
|
|
|
|
def get_pages(self, paths):
|
|
if paths is None:
|
|
raise AttributeError("paths for get_pages can't be None")
|
|
return (self.get(p) for p in paths)
|
|
|
|
def get_sub_pages(self, path):
|
|
def is_subpage(path, root):
|
|
return (path.startswith(root) and # is a subpage
|
|
( re.match('.*index',path) is None) and # is no index
|
|
path_depth(path)<path_depth(root)+2
|
|
)
|
|
return (p for p in self
|
|
if is_subpage(str(p.path),path))
|
|
|
|
# List all index subpages of the current page i.e. all pages in subdirectories
|
|
def get_sub_ipages(self, path):
|
|
cc=path_depth(path)
|
|
ppath="index" if path=="" else pjoin2([path,"index"])
|
|
ps=[p for p in self
|
|
if (p.path.startswith(path) and # subpages of this page
|
|
not ( re.match('.*index',p.path) is None) and # only index
|
|
( ppath != p.path) and # not identical page
|
|
len(p.path.split('/'))<=cc+2) ] # only one level
|
|
return ps
|
|
|
|
|
|
# load a page from a path information
|
|
def get_flatpage(self,path):
|
|
is_index= path=='' or path.split('/')[-1]=='index'
|
|
if path == 'index' or path=='':
|
|
is_index=True
|
|
path=''
|
|
pathi='index'
|
|
else:
|
|
if path.split('/')[-1]=='index': # last element is "index" ?
|
|
is_index=True
|
|
path='/'.join(path.split('/')[0:-1]) # remove index from path
|
|
pathi = u'{}/{}'.format(path, 'index') # try to add index to the path
|
|
page = FlatPages.get(self,pathi) # try to load index page
|
|
if not page is None: # if successful it is a index
|
|
is_index=True
|
|
else:
|
|
page=FlatPages.get(self,path)
|
|
return (is_index, path, page)
|
|
|
|
|
|
def load_lists_for_templates(self, path, is_index):
|
|
path2 = pjoin(FLATPAGES_ROOT,path)
|
|
if is_index == True:
|
|
ld=list_dir_md(path2)
|
|
il=list_dir_img(path2)
|
|
sp=list(get_sub_pages(path))
|
|
spi=list(get_sub_ipages(path))
|
|
else:
|
|
ld=[]
|
|
sp=[]
|
|
spi=[]
|
|
il=[]
|
|
bc=get_bc(path)
|
|
return (ld, il, sp, spi,bc)
|