From 12c02eaac1ab72ec39ff7a3915b0759abac3b263 Mon Sep 17 00:00:00 2001 From: Wesley B <62723358+wesleyboar@users.noreply.github.com> Date: Fri, 13 Sep 2024 14:20:05 -0500 Subject: [PATCH] feat: tup-706 conditionally serve raw content --- taccsite_cms/custom_app_settings.example.py | 2 +- .../middleware/cms_template_middleware.py | 49 +++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) create mode 100644 taccsite_cms/middleware/cms_template_middleware.py diff --git a/taccsite_cms/custom_app_settings.example.py b/taccsite_cms/custom_app_settings.example.py index 3ac04c50d..389b61807 100644 --- a/taccsite_cms/custom_app_settings.example.py +++ b/taccsite_cms/custom_app_settings.example.py @@ -1,3 +1,3 @@ CUSTOM_APPS = ['apps.custom_example'] -CUSTOM_MIDDLEWARE = [] +CUSTOM_MIDDLEWARE = ['taccsite_cms.middleware.cms_template_middleware.CMSTemplateMiddleware'] STATICFILES_DIRS = () diff --git a/taccsite_cms/middleware/cms_template_middleware.py b/taccsite_cms/middleware/cms_template_middleware.py new file mode 100644 index 000000000..6d5ffee70 --- /dev/null +++ b/taccsite_cms/middleware/cms_template_middleware.py @@ -0,0 +1,49 @@ +"""Change CMS page template at runtime""" +import os + +from cms.middleware.toolbar import ToolbarMiddleware +from cms.models.pagemodel import Page as CMS_Page + +BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') + +class CMSTemplateMiddleware(ToolbarMiddleware): + """ + Use a different CMS template than is set for the current page + + Usage: + http://0.0.0.0:8000/news/?raw + http://0.0.0.0:8000/news/?template=raw.html + Applies `raw.html` template + + http://0.0.0.0:8000/news/?template=fullwidth.html + Applies `fulwidth.html` template + + http://0.0.0.0:8000/news/?template=misspelling.html + Raises `TemplateDoesNotExist` error + + http://0.0.0.0:8000/news/?rawng + http://0.0.0.0:8000/news/?template + http://0.0.0.0:8000/news/?template=s + No effect + """ + def __init__(self, get_response): + self.get_response = get_response + + def __call__(self, request): + if ( + hasattr(request, 'current_page') and + isinstance(request.current_page, CMS_Page) + ): + page = request.current_page + query_params = request.GET + query_template = query_params.get('template', '') + + if 'raw' in query_params: + page.template = os.path.join(TEMPLATE_DIR, 'raw.html') + if query_template.endswith('.html'): + page.template = os.path.join(TEMPLATE_DIR, query_template) + + response = self.get_response(request) + + return response