Skip to content

Commit

Permalink
Add url_abs() to allow not unique slugs
Browse files Browse the repository at this point in the history
Management of exceptions to detect dead or ambiguous links
  • Loading branch information
Clément committed Jul 11, 2024
1 parent 0cbb3ba commit 70c4bda
Show file tree
Hide file tree
Showing 11 changed files with 56 additions and 38 deletions.
2 changes: 1 addition & 1 deletion common-content/templates/jinja2/blocks/footer.en.html
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
<div class="col-lg-3 h-100 text-center text-lg-start my-auto">
<ul class="list-unstyled mb-0">
<li class="list-item me-4">
<a href="{{ url_slug('fr-index') }}">Home</a>
<a href="{{ url_abs('en/index') }}">Home</a>
</li>
<li class="list-item me-4">
<a href="{{ url_slug('temoignages-clients') }}">Customer testimonials (FR)</a>
Expand Down
2 changes: 1 addition & 1 deletion common-content/templates/jinja2/blocks/footer.fr.html
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
<div class="col-lg-3 h-100 text-center text-lg-start my-auto">
<ul class="list-unstyled mb-0">
<li class="list-item me-4">
<a href="{{ url_slug('fr-index') }}">Accueil</a>
<a href="{{ url_abs('fr/index') }}">Accueil</a>
</li>
<li class="list-item me-4">
<a href="{{ url_slug('temoignages-clients') }}">Témoignages clients</a>
Expand Down
2 changes: 1 addition & 1 deletion content/templates/jinja2/blocks/navbar.en.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
CTA_LABEL="See pricing",
CTA_TARGET="",
CTA_URL="#pricing",
CHANGE_LANG_URL="fr-index",
CHANGE_LANG_URL="fr/index",
CHANGE_LANG_FLAG_URL="assets/img/lang-fr.svg",
CHANGE_LANG_ALT="Version française"
) }}
2 changes: 1 addition & 1 deletion content/templates/jinja2/blocks/navbar.fr.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
CTA_LABEL="Découvrir les tarifs",
CTA_TARGET="",
CTA_URL="#pricing",
CHANGE_LANG_URL="en-index",
CHANGE_LANG_URL="en/index",
CHANGE_LANG_FLAG_URL="assets/img/lang-gb.svg",
CHANGE_LANG_ALT="English version"
) }}
2 changes: 1 addition & 1 deletion content/templates/jinja2/widgets/navbar.html
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
<div class="navbar__container__right">
<a class="btn btn-sm btn-primary" href="{{ CTA_URL }}"
target="{{ CTA_TARGET }}">{{ CTA_LABEL }}</a>
<a href="{{ url_slug(CHANGE_LANG_URL) }}">
<a href="{{ url_abs(CHANGE_LANG_URL) }}">
<img class="languageFlag" src="{{ static(CHANGE_LANG_FLAG_URL)}}" alt="{{ CHANGE_LANG_ALT }}"/>
</a>
</div>
Expand Down
2 changes: 1 addition & 1 deletion galae-content/pages/en/en-index.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
--- METADATA (first) ---
title galae - ethical and free pay-per-use e-mail
slug en-index
slug index
description galae est un service e-mail éthique et libre facturé à l'usage. Toutes nos offres incluent des boîtes emails et domaines illimités hébergés en France.
language French
lang en
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
--- METADATA (first) ---
title galae - le service e-mail éthique et libre facturé à l'usage
slug fr-index
slug index
description galae est un service e-mail éthique et libre facturé à l'usage. Toutes nos offres incluent des boîtes emails et domaines illimités hébergés en France.
language French
lang fr
Expand Down
39 changes: 30 additions & 9 deletions jssg/jinja2.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,37 @@

from jssg.templatetags.filter_opengraph_metadata import filter_opengraph_metadata

from jssg.models import Document
from django.conf import settings
from jssg.models import Page

def url_from_slug(slug) :
for path in settings.JSSG_PAGES_DIR :
files = path.rglob("*.md")
for f in files :
doc = Document.load(f)
if doc.metadata["slug"] == slug :
return "/" / doc.path.relative_to(path).with_suffix('.html').parent / (doc.metadata["slug"] + ".html")
return ""
url = ""
pages_with_slug = ""

for page in Page.load_glob(all=True) :
if page.slug == slug :
if pages_with_slug == "" :
url = "/" + page.dir + "/" + page.slug + ".html"
else :
url = ""
pages_with_slug += str(page.path.relative_to(page.page_dir.parent)) + ", "

if url == "" and pages_with_slug != "" :
raise Exception("url_slug() : slug '%s' is not unique, found in : [%s] ; use url_abs()" % (slug, pages_with_slug[:-2]))
elif url == "" :
raise Exception("url_slug() : slug '%s' not found" % slug)
return url

def url_absolute(url_path) :
dir = '/'.join(url_path.split('/')[:-1])
slug = ''.join((''.join(url_path.split('/')[-1])).split('.')[0])

for page in Page.get_pages() :
if page["slug"] == slug and dir == "" :
return "/" + slug + ".html"
elif page["slug"] == slug and "dir" in page.keys() and page["dir"] == dir :
return "/" + dir + "/" + slug + ".html"

raise Exception("url_abs() : page for %s url not found" % url_path)

def environment(**options):
env = Environment(**options)
Expand All @@ -24,6 +44,7 @@ def environment(**options):
"static": static,
"url": reverse,
"url_slug": url_from_slug,
"url_abs" : url_absolute
}
)
env.filters.update(
Expand Down
24 changes: 13 additions & 11 deletions jssg/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,10 +239,11 @@ def __init__(self, content: str, **metadata) -> None:
except KeyError:
self.slug = slugify(self.title)

p = self.path
while (p not in self.BASE_DIR) :
p = p.parent
self.dir = str(self.path.relative_to(p).parent)
self.page_dir = self.path
while (self.page_dir not in self.BASE_DIR) :
self.page_dir = self.page_dir.parent

self.dir = str(self.path.relative_to(self.page_dir).parent)
if self.dir == '.' :
self.dir = ''

Expand All @@ -256,6 +257,10 @@ def load_glob(
) -> Iterator["Page"]:
"""Overridden only to make the static typing happy."""
return super().load_glob(path, dir, glob, all)

@classmethod
def get_pages(cls) :
return ({"slug": p.slug} if p.dir == '' else {"dir": p.dir, "slug" : p.slug} for p in Page.load_glob(all = True))


class Post(Page):
Expand All @@ -272,16 +277,13 @@ def __init__(self, content: str, **metadata) -> None:
super().__init__(content, **metadata)
self.timestamp = datetime.datetime.fromisoformat(metadata["date"])

p = self.path
while (p not in self.BASE_DIR) :
p = p.parent
self.dir = str(self.path.relative_to(p).parent)
if self.dir == '.' :
self.dir = ''

@classmethod
def load_glob(
cls, path: Optional[List[Path]] = None, dir = "", glob: str = "*.md", all = False
) -> Iterator["Post"]:
"""Overridden only to make the static typing happy."""
return super().load_glob(path, dir, glob, all)

@classmethod
def get_posts(cls) :
return ({"slug": p.slug} if p.dir == '' else {"dir": p.dir, "slug" : p.slug} for p in Post.load_glob(all = True))
15 changes: 5 additions & 10 deletions jssg/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,8 @@
from jssg.models import Page, Post
from jssg import settings

def get_pages() :
return ({"slug": p.slug} if p.dir == '' else {"dir": p.dir, "slug" : p.slug} for p in Page.load_glob(all = True))

def get_posts() :
return ({"slug": p.slug} if p.dir == '' else {"dir": p.dir, "slug" : p.slug} for p in Post.load_glob(all = True))

print([p for p in get_pages()])
# print([p for p in Page.get_pages()])

urlpatterns = [
distill_path(
Expand All @@ -35,24 +30,24 @@ def get_posts() :
r'^(?!posts/)(?P<slug>[a-zA-Z0-9-]+).html$',
views.PageView.as_view(),
name="page",
distill_func=get_pages,
distill_func=Page.get_pages,
),
distill_re_path(
r'^(?!posts/)(?P<dir>[a-zA-Z-/]+)/(?P<slug>[a-zA-Z0-9-]+).html$',
views.PageView.as_view(),
name="page",
distill_func=get_pages,
distill_func=Page.get_pages,
),
distill_path(
"posts/<slug:slug>.html",
views.PostView.as_view(),
name="post",
distill_func=get_posts,
distill_func=Post.get_posts,
),
distill_path(
"posts/<path:dir>/<slug:slug>.html",
views.PostView.as_view(),
name="post",
distill_func=get_posts,
distill_func=Post.get_posts,
)
]
2 changes: 1 addition & 1 deletion jssg/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ class IndexView(PageView):

def get_object(self, queryset=None) -> Model:
self.kwargs["dir"] = "en"
self.kwargs["slug"] = "en-index"
self.kwargs["slug"] = "index"
return super().get_object(queryset)


Expand Down

0 comments on commit 70c4bda

Please sign in to comment.