Skip to content

Commit

Permalink
Index page and additional filters settings (#54)
Browse files Browse the repository at this point in the history
* Add JFME_INDEX_PAGE setting

* Add JFME_ADDITIONAL_JINJA2_FUNCTIONS and JFME_ADDITIONAL_JINJA2_FILTERS settings

* Update doc

* Move Jinja2 function url_for_slug and url_for_slug_path in jssg/templatetags/

---------

Co-authored-by: Clément <[email protected]>
  • Loading branch information
ClmntBcqt and Clément authored Aug 7, 2024
1 parent 2b617e5 commit 977229b
Show file tree
Hide file tree
Showing 5 changed files with 151 additions and 84 deletions.
9 changes: 6 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,18 +53,21 @@ For django settings, see https://docs.djangoproject.com/en/5.0/ref/settings/
Otherwise, you have to configure the following settings :
- `JFME_DOMAIN` : the domain name of your website, for instance `"https://www.example.com"` (used in sitemap file)
- `JFME_CONTENT_DIRS` : a list of directories where to look for the site content
- `JFME_PAGE_INDEX` : the page that will be printed at url `"/"`, for instance `"fr/index/accueil"` will be the page in `pages/fr/index/` with the slug `accueil`

Other useful settings :
- Default metadata : `JFME_DEFAULT_METADATA_DICT` and `JFME_DEFAULT_METADATA_FILEPATH` allow to set default metadata for pages and posts. The first one is a python dictionary and the second one is a Path to a file having the same format as metadata section in pages.
The order, from less to most priority is : `JFME_DEFAULT_METADATA_DICT` then `JFME_DEFAULT_METADATA_FILEPATH` then page matadata.
- Posts pagination : `JFME_NUMBER_OF_POSTS_BY_PAGE` give the maximum number of posts in a posts list page. If set to 0 or -1, all posts will be in the first page.
- `JFME_ADDITIONAL_JINJA2_FUNCTIONS` : a dict of function name as key and string of python module as value, to add Jinja2 functions. \
For instance `{"base64encode": "jssg.templatetags.base_64.base64encode", "md_readtime": "readtime.of_markdown"}` will add :
- the `base64encode` function in `jssg/templatetags/base_64.py`
- `of_markdown` function of `readtime` module as `md_readtime` Jinja2 function
- `JFME_ADDITIONAL_JINJA2_FILTERS` same as `JFME_ADDITIONAL_JINJA2_FUNCTIONS`, but for Jinja2 filters

### `Dockerfile` :
- In the `# Copy source dir` section, add `COPY <content-dir>/ <content-dir>/` for each content directory in `JFME_CONTENT_DIRS`

### `views.py` :
- In the `get_object` method of `IndexView`, set the `self.kwargs["slug"]` to the slug of your index page which is sent at the root of your site

## Usage

Each directory defined in `JFME_CONTENT_DIRS` has the following structure :
Expand Down
137 changes: 59 additions & 78 deletions jssg/jinja2.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,88 +2,14 @@
from django.urls import reverse
from django_jinja_markdown.templatetags.md import markdown
from jinja2 import Environment
from django.core.management.base import BaseCommand

from jssg.templatetags.filter_opengraph_metadata import filter_opengraph_metadata
from jssg.templatetags.functions_url import url_for_slug, url_for_slug_path

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

import re

def url_for_slug(slug) :
"""
@param slug: the slug of the page to search
@return: the string of the url corresponding to the page
@error: raise an exception if the slug does not exist or it is not unique (eg same slug found in several folders)
>>> url_for_slug('index') # the slug exists and is unique
/en/index.html
>>> url_for_slug('index-duplicated') # the slug exists in several pages
Traceback (most recent call last):
...
Exception: slug 'index-duplicated' is not unique, found in : [pages/fr-index.md, pages/en-index.md] ; use url_for_slug_path()
>>> url_for_slug('index-removed') # the slug does not exists
Traceback (most recent call last):
...
Exception: slug 'index-removed' not found
"""

url = ""
pages_with_slug = []

for page in Page.load_glob(all=True) :
if page.slug == slug : # the page exists
if pages_with_slug == [] : # the slug has not been found yet
if page.rel_folder_path != '' :
url = "/" + page.rel_folder_path + "/" + page.slug + ".html"
else :
url = "/" + page.slug + ".html"
else : # the slug already exists
url = ""
pages_with_slug.append(str(page.path.relative_to(page.content_page_dir.parent)))

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

def url_for_slug_path(url_path) :
"""
@param url_path: the url of the page to search (absolute path)
@return: the string of the slug url corresponding to the page
@error: raise an exception if the url is a dead link
>>> url_for_slug_path('/en/index') # the page exists
/en/index.html
>>> url_for_slug_path('/en/index-removed') # the page does not exist
Traceback (most recent call last):
...
Exception: page for '/en/index-removed' url not found (dead link)
>>> url_for_slug_path('folder/index')
Traceback (most recent call last):
...
Exception: url 'folder/index' is not valid ; correct urls are /<dir>/<slug> or /<slug>
"""
# Valid url are /<dir>/<slug>.html or /<slug>.html
# Example: if url_path is "/tmp/folder/subfolder/thefile.html", then slug will be "thefile" and the dir will be "tmp/folder/subfolder"
# Note : the dir does not start with '/' since the url parsed in url.py do not either
try :
_, dir, slug = re.findall(r"(^|^/([a-zA-Z0-9/-]+))/([a-zA-Z0-9-]+)$", url_path)[0]
except :
raise Exception("url '%s' is not valid ; correct urls are /<dir>/<slug> or /<slug>" % url_path)

# Verify that the page exists
for page in Page.load_glob(all=True) :
if page.slug == slug and page.rel_folder_path == dir :
return url_path + ".html"

raise Exception("page for '%s' url not found (dead link)" % url_path)
import importlib

def environment(**options):
env = Environment(**options)
Expand All @@ -101,4 +27,59 @@ def environment(**options):
"filter_opengraph_metadata" : filter_opengraph_metadata
}
)

for templatetag in settings.JFME_ADDITIONAL_JINJA2_FUNCTIONS :
module_name, function_name = settings.JFME_ADDITIONAL_JINJA2_FUNCTIONS[templatetag].rsplit('.', 1)
try :
module = importlib.import_module(module_name)
function = getattr(module, function_name)
except(Exception) :
command = BaseCommand()
command.stdout.write(
command.style.ERROR(
"Error: JFME_ADDITIONAL_JINJA2_FUNCTIONS: couldn't import '" + settings.JFME_ADDITIONAL_JINJA2_FUNCTIONS[templatetag] +"'"
)
)
else :
if templatetag not in env.globals :
env.globals.update(
{
templatetag: function
}
)
else :
command = BaseCommand()
command.stdout.write(
command.style.ERROR(
"Error: JFME_ADDITIONAL_JINJA2_FUNCTIONS: '" + templatetag + "' function already exists"
)
)

for templatetag in settings.JFME_ADDITIONAL_JINJA2_FILTERS :
module_name, function_name = settings.JFME_ADDITIONAL_JINJA2_FILTERS[templatetag].rsplit('.', 1)
try :
module = importlib.import_module(module_name)
function = getattr(module, function_name)
except(Exception) :
command = BaseCommand()
command.stdout.write(
command.style.ERROR(
"Error: JFME_ADDITIONAL_JINJA2_FILTERS: couldn't import '" + settings.JFME_ADDITIONAL_JINJA2_FILTERS[templatetag] +"'"
)
)
else :
if templatetag not in env.filters :
env.filters.update(
{
templatetag: function
}
)
else :
command = BaseCommand()
command.stdout.write(
command.style.ERROR(
"Error: JFME_ADDITIONAL_JINJA2_FILTERS: '" + templatetag + "' filter already exists"
)
)

return env
5 changes: 3 additions & 2 deletions jssg/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,9 @@
JFME_NUMBER_OF_POSTS_BY_PAGE = 3 # no pagination of posts if set to 0 or -1
JFME_CONTENT_REQUIRED_METADATA = ["title", "slug", "lang", "description"]
JFME_SITEMAP_LASTMOD_DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S%z" # strftime format, see https://docs.python.org/fr/3.6/library/datetime.html#strftime-and-strptime-behavior, see https://www.sitemaps.org/protocol.html#lastmoddef for allowed datetime formats


JFME_INDEX_PAGE = "fr-index"
JFME_ADDITIONAL_JINJA2_FUNCTIONS = {}
JFME_ADDITIONAL_JINJA2_FILTERS = {}
#Django sites and sitemap app
SITE_ID = 1

Expand Down
78 changes: 78 additions & 0 deletions jssg/templatetags/functions_url.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import re
from jssg.models import Page

def url_for_slug(slug) :
"""
@param slug: the slug of the page to search
@return: the string of the url corresponding to the page
@error: raise an exception if the slug does not exist or it is not unique (eg same slug found in several folders)
>>> url_for_slug('index') # the slug exists and is unique
/en/index.html
>>> url_for_slug('index-duplicated') # the slug exists in several pages
Traceback (most recent call last):
...
Exception: slug 'index-duplicated' is not unique, found in : [pages/fr-index.md, pages/en-index.md] ; use url_for_slug_path()
>>> url_for_slug('index-removed') # the slug does not exists
Traceback (most recent call last):
...
Exception: slug 'index-removed' not found
"""

url = ""
pages_with_slug = []

for page in Page.load_glob(all=True) :
if page.slug == slug : # the page exists
if pages_with_slug == [] : # the slug has not been found yet
if page.rel_folder_path != '' :
url = "/" + page.rel_folder_path + "/" + page.slug + ".html"
else :
url = "/" + page.slug + ".html"
else : # the slug already exists
url = ""
pages_with_slug.append(str(page.path.relative_to(page.content_page_dir.parent)))

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

def url_for_slug_path(url_path) :
"""
@param url_path: the url of the page to search (absolute path)
@return: the string of the slug url corresponding to the page
@error: raise an exception if the url is a dead link
>>> url_for_slug_path('/en/index') # the page exists
/en/index.html
>>> url_for_slug_path('/en/index-removed') # the page does not exist
Traceback (most recent call last):
...
Exception: page for '/en/index-removed' url not found (dead link)
>>> url_for_slug_path('folder/index')
Traceback (most recent call last):
...
Exception: url 'folder/index' is not valid ; correct urls are /<dir>/<slug> or /<slug>
"""
# Valid url are /<dir>/<slug>.html or /<slug>.html
# Example: if url_path is "/tmp/folder/subfolder/thefile.html", then slug will be "thefile" and the dir will be "tmp/folder/subfolder"
# Note : the dir does not start with '/' since the url parsed in url.py do not either
try :
_, dir, slug = re.findall(r"(^|^/([a-zA-Z0-9/-]+))/([a-zA-Z0-9-]+)$", url_path)[0]
except :
raise Exception("url '%s' is not valid ; correct urls are /<dir>/<slug> or /<slug>" % url_path)

# Verify that the page exists
for page in Page.load_glob(all=True) :
if page.slug == slug and page.rel_folder_path == dir :
return url_path + ".html"

raise Exception("page for '%s' url not found (dead link)" % url_path)
6 changes: 5 additions & 1 deletion jssg/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from django.views.generic import DetailView

from jssg.models import Page, Post, PostList
from django.conf import settings


class PostFeedsView(Feed):
Expand Down Expand Up @@ -64,7 +65,10 @@ class IndexView(PageView):
template_name = "page.html"

def get_object(self, queryset=None) -> Model:
self.kwargs["slug"] = "en-index"
if len(settings.JFME_INDEX_PAGE.rsplit('/', 1)) > 1 :
self.kwargs['dir'], self.kwargs['slug'] = settings.JFME_INDEX_PAGE.rsplit('/', 1)
else :
self.kwargs['dir'], self.kwargs['slug'] = "", settings.JFME_INDEX_PAGE.rsplit('/', 1)[0]
return super().get_object(queryset)


Expand Down

0 comments on commit 977229b

Please sign in to comment.