1- from typing import Dict
1+ from typing import Dict , Union
22
33from django import template
4+ from django .core .handlers .wsgi import WSGIRequest
45from django .template .base import Node
56from django .template .exceptions import TemplateSyntaxError
67from django .template .loader_tags import construct_relative_path
1718register = template .Library ()
1819
1920
21+ class NoParentError (Exception ):
22+ pass
23+
24+
2025@register .simple_tag (takes_context = True )
21- def directory_contents (context , directory : str = None ) -> Dict [str , str ]:
26+ def directory_contents (
27+ context , directory : str = None , exclude : str = None
28+ ) -> Dict [str , str ]:
2229 if not directory :
2330 request = context ["request" ]
2431 directory = request .path
25-
26- if directory .startswith ("/" ):
27- directory = directory [1 :]
2832 elif isinstance (directory , SafeString ):
2933 # Force SafeString to be a normal string so it can be used with `Path` later
3034 directory = directory + ""
3135
36+ if directory .startswith ("/" ):
37+ directory = directory [1 :]
38+
3239 content_paths = get_content_paths (directory )
3340 contents = []
3441
@@ -42,10 +49,12 @@ def directory_contents(context, directory: str = None) -> Dict[str, str]:
4249 content_slug = f"{ directory } /{ path_slug } "
4350 content_directory = content_directory / directory
4451
45- directory_without_name = str (path ).replace (path .name , "" )[:- 1 ]
52+ if exclude :
53+ if exclude .startswith ("/" ):
54+ exclude = exclude [1 :]
4655
47- if str ( content_directory ) != directory_without_name :
48- continue
56+ if exclude == content_slug :
57+ continue
4958
5059 (_ , metadata ) = get_html_and_markdown (content_slug )
5160
@@ -54,6 +63,26 @@ def directory_contents(context, directory: str = None) -> Dict[str, str]:
5463 return contents
5564
5665
66+ @register .filter ()
67+ def parent (path : Union [str , WSGIRequest ] = "" ) -> str :
68+ if hasattr (path , "path" ):
69+ # Handle if a `request` is passed in
70+ path = path .path
71+
72+ path = path .strip ()
73+
74+ if path .endswith ("/" ):
75+ path = path [:- 1 ]
76+
77+ if path == "" :
78+ raise NoParentError ()
79+
80+ last_slash_index = path .rindex ("/" )
81+ path = path [:last_slash_index ]
82+
83+ return path
84+
85+
5786class IncludeMarkdownNode (Node ):
5887 """
5988 Based on: `django.template.loader_tags.IncludeNode`.
0 commit comments