From 82daedc766dc3986dc9ac17ea8a6b3da87a6b1ac Mon Sep 17 00:00:00 2001 From: kosayoda Date: Tue, 23 Mar 2021 23:17:55 +0800 Subject: Simplify content app. Rather than having two views for the base page and all other pages, all pages now use the same view. The view context handler is simplified to take advantage of pathlib features. The markdown folder is now /content/resources/* rather than /content/resources/content/*, as the latter is unnecessary nesting. --- pydis_site/apps/content/resources/_info.yml | 2 + .../content/resources/content/guides/_info.yml | 2 - .../content/guides/pydis-guides/_info.yml | 2 - .../guides/pydis-guides/how-to-write-a-article.md | 80 ---------------------- pydis_site/apps/content/resources/guides/_info.yml | 2 + .../resources/guides/pydis-guides/_info.yml | 2 + .../guides/pydis-guides/how-to-write-a-article.md | 80 ++++++++++++++++++++++ pydis_site/apps/content/urls.py | 2 +- pydis_site/apps/content/utils.py | 42 ++++-------- pydis_site/apps/content/views/__init__.py | 3 +- pydis_site/apps/content/views/page_category.py | 61 +++++++---------- pydis_site/apps/content/views/pages.py | 16 ----- pydis_site/settings.py | 2 +- pydis_site/templates/content/listing.html | 5 +- pydis_site/templates/content/page.html | 1 - 15 files changed, 127 insertions(+), 175 deletions(-) create mode 100644 pydis_site/apps/content/resources/_info.yml delete mode 100644 pydis_site/apps/content/resources/content/guides/_info.yml delete mode 100644 pydis_site/apps/content/resources/content/guides/pydis-guides/_info.yml delete mode 100644 pydis_site/apps/content/resources/content/guides/pydis-guides/how-to-write-a-article.md create mode 100644 pydis_site/apps/content/resources/guides/_info.yml create mode 100644 pydis_site/apps/content/resources/guides/pydis-guides/_info.yml create mode 100644 pydis_site/apps/content/resources/guides/pydis-guides/how-to-write-a-article.md delete mode 100644 pydis_site/apps/content/views/pages.py (limited to 'pydis_site') diff --git a/pydis_site/apps/content/resources/_info.yml b/pydis_site/apps/content/resources/_info.yml new file mode 100644 index 00000000..4ccdd7e1 --- /dev/null +++ b/pydis_site/apps/content/resources/_info.yml @@ -0,0 +1,2 @@ +name: Pages +description: Guides, articles and pages hosted on the site. diff --git a/pydis_site/apps/content/resources/content/guides/_info.yml b/pydis_site/apps/content/resources/content/guides/_info.yml deleted file mode 100644 index 369f05d4..00000000 --- a/pydis_site/apps/content/resources/content/guides/_info.yml +++ /dev/null @@ -1,2 +0,0 @@ -name: Guides -description: Python and PyDis guides. diff --git a/pydis_site/apps/content/resources/content/guides/pydis-guides/_info.yml b/pydis_site/apps/content/resources/content/guides/pydis-guides/_info.yml deleted file mode 100644 index 64111a83..00000000 --- a/pydis_site/apps/content/resources/content/guides/pydis-guides/_info.yml +++ /dev/null @@ -1,2 +0,0 @@ -name: Python Discord Guides -description: Python Discord server and community guides. diff --git a/pydis_site/apps/content/resources/content/guides/pydis-guides/how-to-write-a-article.md b/pydis_site/apps/content/resources/content/guides/pydis-guides/how-to-write-a-article.md deleted file mode 100644 index ec89988c..00000000 --- a/pydis_site/apps/content/resources/content/guides/pydis-guides/how-to-write-a-article.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -title: How to Write a Article -short_description: Learn how to write a article for this website -icon_class: fas -icon: fa-info ---- - -When you are interested about how to write articles for this site (like this), then you can learn about it here. -PyDis use Markdown (GitHub Markdown) files for articles. - -## Getting Started -Before you can get started with writing a article, you need idea. -Best way to find out is your idea good is to discuss about it in #dev-contrib channel. There can other peoples give their opinion about your idea. Even better, open issue in site repository first, then PyDis staff can see it and approve/decline this idea. -It's good idea to wait for staff decision before starting to write guide to avoid case when you write a long long article, but then this don't get approved. - -To start with contributing, you should read [how to contribute to site](https://pythondiscord.com/pages/contributing/site/). -You should also read our [Git workflow](https://pythondiscord.com/pages/contributing/working-with-git/), because you need to push your guide to GitHub. - -## Creating a File -All articles is located at `site` repository, in `pydis_site/apps/content/resources/content`. Under this is root level articles (.md files) and categories (directories). Learn more about categories in [categories section](#categories). - -When you are writing guides, then these are located under `guides` category. - -At this point, you will need your article name for filename. Replace all your article name spaces with `-` and make all lowercase. Save this as `.md` (Markdown) file. This name (without Markdown extension) is path of article in URL. - -## Markdown Metadata -Article files have some required metadata, like title, description, relevant pages. Metadata is first thing in file, YAML-like key-value pairs: - -```md ---- -title: My Article -short_description: This is my short description. -relevant_links: url1,url2,url3 -relevant_link_values: Text for url1,Text for url2,Text for url3 ---- - -Here comes content of article... -``` - -You can read more about Markdown metadata [here](https://github.com/trentm/python-markdown2/wiki/metadata). - -### Fields -- **Name:** Easily-readable name for your article. -- **Short Description:** Small, 1-2 line description that describe what your article explain. -- **Relevant Links and Values:** URLs and values is under different fields, separated with comma. -- **Icon class:** `icon_class` field have one of the favicons classes. Default is `fab`. -- **Icon:** `icon` field have favicon name. Default `fa-python`. - -## Content -For content, mostly you can use standard markdown, but there is a few addition that is available. - -### IDs for quick jumps -System automatically assign IDs to headers, so like this header will get ID `ids-for-quick-jumps`. - -### Tables -Tables like in GitHub is supported too: - -| This is header | This is too header | -| -------------- | ------------------ | -| My item | My item too | - -### Codeblocks -Also this system supports codeblocks and provides syntax highlighting with `highlight.js`. -To activate syntax highlight, just put language directly after starting backticks. - -```py -import os - -path = os.path.join("foo", "bar") -``` - -## Categories -To have some systematic sorting of guides, site support guides categories. Currently this system support only 1 level of categories. Categories live at `site` repo in `pydis_site/apps/content/resources/content` subdirectories. Directory name is path of category in URL. Inside category directory, there is 1 file required: `_info.yml`. This file need 2 key-value pairs defined: - -```yml -name: Category name -description: Category description -``` - -Then all Markdown files in this folder will be under this category. diff --git a/pydis_site/apps/content/resources/guides/_info.yml b/pydis_site/apps/content/resources/guides/_info.yml new file mode 100644 index 00000000..369f05d4 --- /dev/null +++ b/pydis_site/apps/content/resources/guides/_info.yml @@ -0,0 +1,2 @@ +name: Guides +description: Python and PyDis guides. diff --git a/pydis_site/apps/content/resources/guides/pydis-guides/_info.yml b/pydis_site/apps/content/resources/guides/pydis-guides/_info.yml new file mode 100644 index 00000000..64111a83 --- /dev/null +++ b/pydis_site/apps/content/resources/guides/pydis-guides/_info.yml @@ -0,0 +1,2 @@ +name: Python Discord Guides +description: Python Discord server and community guides. diff --git a/pydis_site/apps/content/resources/guides/pydis-guides/how-to-write-a-article.md b/pydis_site/apps/content/resources/guides/pydis-guides/how-to-write-a-article.md new file mode 100644 index 00000000..ec89988c --- /dev/null +++ b/pydis_site/apps/content/resources/guides/pydis-guides/how-to-write-a-article.md @@ -0,0 +1,80 @@ +--- +title: How to Write a Article +short_description: Learn how to write a article for this website +icon_class: fas +icon: fa-info +--- + +When you are interested about how to write articles for this site (like this), then you can learn about it here. +PyDis use Markdown (GitHub Markdown) files for articles. + +## Getting Started +Before you can get started with writing a article, you need idea. +Best way to find out is your idea good is to discuss about it in #dev-contrib channel. There can other peoples give their opinion about your idea. Even better, open issue in site repository first, then PyDis staff can see it and approve/decline this idea. +It's good idea to wait for staff decision before starting to write guide to avoid case when you write a long long article, but then this don't get approved. + +To start with contributing, you should read [how to contribute to site](https://pythondiscord.com/pages/contributing/site/). +You should also read our [Git workflow](https://pythondiscord.com/pages/contributing/working-with-git/), because you need to push your guide to GitHub. + +## Creating a File +All articles is located at `site` repository, in `pydis_site/apps/content/resources/content`. Under this is root level articles (.md files) and categories (directories). Learn more about categories in [categories section](#categories). + +When you are writing guides, then these are located under `guides` category. + +At this point, you will need your article name for filename. Replace all your article name spaces with `-` and make all lowercase. Save this as `.md` (Markdown) file. This name (without Markdown extension) is path of article in URL. + +## Markdown Metadata +Article files have some required metadata, like title, description, relevant pages. Metadata is first thing in file, YAML-like key-value pairs: + +```md +--- +title: My Article +short_description: This is my short description. +relevant_links: url1,url2,url3 +relevant_link_values: Text for url1,Text for url2,Text for url3 +--- + +Here comes content of article... +``` + +You can read more about Markdown metadata [here](https://github.com/trentm/python-markdown2/wiki/metadata). + +### Fields +- **Name:** Easily-readable name for your article. +- **Short Description:** Small, 1-2 line description that describe what your article explain. +- **Relevant Links and Values:** URLs and values is under different fields, separated with comma. +- **Icon class:** `icon_class` field have one of the favicons classes. Default is `fab`. +- **Icon:** `icon` field have favicon name. Default `fa-python`. + +## Content +For content, mostly you can use standard markdown, but there is a few addition that is available. + +### IDs for quick jumps +System automatically assign IDs to headers, so like this header will get ID `ids-for-quick-jumps`. + +### Tables +Tables like in GitHub is supported too: + +| This is header | This is too header | +| -------------- | ------------------ | +| My item | My item too | + +### Codeblocks +Also this system supports codeblocks and provides syntax highlighting with `highlight.js`. +To activate syntax highlight, just put language directly after starting backticks. + +```py +import os + +path = os.path.join("foo", "bar") +``` + +## Categories +To have some systematic sorting of guides, site support guides categories. Currently this system support only 1 level of categories. Categories live at `site` repo in `pydis_site/apps/content/resources/content` subdirectories. Directory name is path of category in URL. Inside category directory, there is 1 file required: `_info.yml`. This file need 2 key-value pairs defined: + +```yml +name: Category name +description: Category description +``` + +Then all Markdown files in this folder will be under this category. diff --git a/pydis_site/apps/content/urls.py b/pydis_site/apps/content/urls.py index 1406f672..c11b222a 100644 --- a/pydis_site/apps/content/urls.py +++ b/pydis_site/apps/content/urls.py @@ -4,6 +4,6 @@ from . import views app_name = "content" urlpatterns = [ - path("", views.PagesView.as_view(), name='pages'), + path("", views.PageOrCategoryView.as_view(), name='pages'), path("/", views.PageOrCategoryView.as_view(), name='page_category'), ] diff --git a/pydis_site/apps/content/utils.py b/pydis_site/apps/content/utils.py index db502a71..ef02a8cb 100644 --- a/pydis_site/apps/content/utils.py +++ b/pydis_site/apps/content/utils.py @@ -1,65 +1,49 @@ -import os -from typing import Dict, List, Optional, Union +from pathlib import Path +from typing import Dict, Union import yaml -from django.conf import settings from django.http import Http404 from markdown2 import markdown -def get_category(path: List[str]) -> Dict[str, str]: +def get_category(path: Path) -> Dict[str, str]: """Load category information by name from _info.yml.""" - path = settings.PAGES_PATH.joinpath(*path) if not path.exists() or not path.is_dir(): raise Http404("Category not found.") return yaml.safe_load(path.joinpath("_info.yml").read_text()) -def get_categories(path: Optional[List[str]] = None) -> Dict[str, Dict]: +def get_categories(path: Path) -> Dict[str, Dict]: """Get all categories information.""" categories = {} - if path is None: - categories_path = settings.PAGES_PATH - path = [] - else: - categories_path = settings.PAGES_PATH.joinpath(*path) - for name in categories_path.iterdir(): + for name in path.iterdir(): if name.is_dir(): - categories[name.name] = get_category([*path, name.name]) + categories[name.name] = get_category(path.joinpath(name.name)) return categories -def get_pages(path: Optional[List[str]] = None) -> Dict[str, Dict]: - """Get all root or category pages.""" - if path is None: - base_dir = settings.PAGES_PATH - else: - base_dir = settings.PAGES_PATH.joinpath(*path) - +def get_pages(path: Path) -> Dict[str, Dict]: + """Get all root or category page names and their metadata.""" pages = {} - for item in base_dir.iterdir(): + for item in path.iterdir(): if item.is_file() and item.name.endswith(".md"): md = markdown(item.read_text(), extras=["metadata"]) - pages[os.path.splitext(item.name)[0]] = md.metadata + pages[item.stem] = md.metadata return pages -def get_page(path: List[str]) -> Dict[str, Union[str, Dict]]: +def get_page(path: Path) -> Dict[str, Union[str, Dict]]: """Get one specific page. When category is specified, get it from there.""" - page_path = settings.PAGES_PATH.joinpath(*path[:-1]) - - # We need to include extension MD - page_path = page_path.joinpath(f"{path[-1]}.md") - if not page_path.exists() or not page_path.is_file(): + if not path.exists() or not path.is_file(): raise Http404("Page not found.") html = markdown( - page_path.read_text(), + path.read_text(), extras=[ "metadata", "fenced-code-blocks", diff --git a/pydis_site/apps/content/views/__init__.py b/pydis_site/apps/content/views/__init__.py index 740d98e9..70ea1c7a 100644 --- a/pydis_site/apps/content/views/__init__.py +++ b/pydis_site/apps/content/views/__init__.py @@ -1,4 +1,3 @@ from .page_category import PageOrCategoryView -from .pages import PagesView -__all__ = ["PageOrCategoryView", "PagesView"] +__all__ = ["PageOrCategoryView"] diff --git a/pydis_site/apps/content/views/page_category.py b/pydis_site/apps/content/views/page_category.py index f00a79ee..7e04e2f3 100644 --- a/pydis_site/apps/content/views/page_category.py +++ b/pydis_site/apps/content/views/page_category.py @@ -1,4 +1,5 @@ import typing as t +from pathlib import Path from django.conf import settings from django.http import Http404 @@ -10,14 +11,18 @@ from pydis_site.apps.content import utils class PageOrCategoryView(TemplateView): """Handles pages and page categories.""" + def dispatch(self, request: t.Any, *args, **kwargs) -> t.Any: + """Conform URL path location to the filesystem path.""" + self.location = Path(self.kwargs.get("location", "")) + self.full_location = settings.PAGES_PATH / self.location + + return super().dispatch(request, *args, **kwargs) + def get_template_names(self) -> t.List[str]: """Checks does this use page template or listing template.""" - location = self.kwargs["location"].split("/") - full_location = settings.PAGES_PATH.joinpath(*location) - - if full_location.is_dir(): + if self.full_location.is_dir(): template_name = "content/listing.html" - elif full_location.with_suffix(".md").is_file(): + elif self.full_location.with_suffix(".md").is_file(): template_name = "content/page.html" else: raise Http404 @@ -28,42 +33,24 @@ class PageOrCategoryView(TemplateView): """Assign proper context variables based on what resource user requests.""" context = super().get_context_data(**kwargs) - location: list = self.kwargs["location"].split("/") - full_location = settings.PAGES_PATH.joinpath(*location) - - if full_location.is_dir(): - context["category_info"] = utils.get_category(location) - context["content"] = utils.get_pages(location) - context["categories"] = utils.get_categories(location) - # Add trailing slash here to simplify template - context["path"] = "/".join(location) + "/" - context["in_category"] = True - elif full_location.with_suffix(".md").is_file(): - page_result = utils.get_page(location) - - if len(location) > 1: - context["category_data"] = utils.get_category(location[:-1]) - context["category_data"]["raw_name"] = location[:-1][-1] - else: - context["category_data"] = {"name": None, "raw_name": None} - + if self.full_location.is_dir(): + context["categories"] = utils.get_categories(self.full_location) + context["category_info"] = utils.get_category(self.full_location) + context["content"] = utils.get_pages(self.full_location) + context["path"] = f"{self.location}/" # Add trailing slash here to simplify template + elif self.full_location.with_suffix(".md").is_file(): + page_result = utils.get_page(self.full_location.with_suffix(".md")) context["page"] = page_result context["relevant_links"] = page_result["metadata"].get("relevant_links", {}) else: raise Http404 - location.pop() - breadcrumb_items = [] - while len(location): - breadcrumb_items.insert( - 0, - { - "name": utils.get_category(location)["name"], - "path": "/".join(location) - } - ) - location.pop() - - context["breadcrumb_items"] = breadcrumb_items + breadcrumb_items = [ + { + "name": utils.get_category(settings.PAGES_PATH / location)["name"], + "path": str(location) + } for location in self.location.parents + ] + context["breadcrumb_items"] = reversed(breadcrumb_items) return context diff --git a/pydis_site/apps/content/views/pages.py b/pydis_site/apps/content/views/pages.py deleted file mode 100644 index 11ac0eeb..00000000 --- a/pydis_site/apps/content/views/pages.py +++ /dev/null @@ -1,16 +0,0 @@ -from django.views.generic import TemplateView - -from pydis_site.apps.content.utils import get_pages, get_categories - - -class PagesView(TemplateView): - """Shows all pages and categories.""" - - template_name = "content/listing.html" - - def get_context_data(self, **kwargs) -> dict: - """Add page and category data to template context.""" - context = super().get_context_data(**kwargs) - context["content"] = get_pages() - context["categories"] = get_categories() - return context diff --git a/pydis_site/settings.py b/pydis_site/settings.py index 0b4d9fd1..3abf556a 100644 --- a/pydis_site/settings.py +++ b/pydis_site/settings.py @@ -287,4 +287,4 @@ SITE_REPOSITORY_OWNER = "python-discord" SITE_REPOSITORY_NAME = "site" SITE_REPOSITORY_BRANCH = "master" -PAGES_PATH = Path(BASE_DIR, "pydis_site", "apps", "content", "resources", "content") +PAGES_PATH = Path(BASE_DIR, "pydis_site", "apps", "content", "resources") diff --git a/pydis_site/templates/content/listing.html b/pydis_site/templates/content/listing.html index 39eae1c2..097cac4f 100644 --- a/pydis_site/templates/content/listing.html +++ b/pydis_site/templates/content/listing.html @@ -16,13 +16,10 @@
diff --git a/pydis_site/templates/content/page.html b/pydis_site/templates/content/page.html index 3b0ebb5f..433baa69 100644 --- a/pydis_site/templates/content/page.html +++ b/pydis_site/templates/content/page.html @@ -20,7 +20,6 @@