diff --git a/taccsite_cms/custom_app_settings.example.py b/taccsite_cms/custom_app_settings.example.py index 4bc48c268..842078f63 100644 --- a/taccsite_cms/custom_app_settings.example.py +++ b/taccsite_cms/custom_app_settings.example.py @@ -11,5 +11,5 @@ 'djangocms_blog', ] -CUSTOM_MIDDLEWARE = [] +CUSTOM_MIDDLEWARE = ['taccsite_cms.middleware.cms_template.CMSTemplateMiddleware'] STATICFILES_DIRS = () diff --git a/taccsite_cms/middleware/cms_template.py b/taccsite_cms/middleware/cms_template.py new file mode 100644 index 000000000..6d5ffee70 --- /dev/null +++ b/taccsite_cms/middleware/cms_template.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