Skip to content

Instantly share code, notes, and snippets.

@bq1990
Forked from bgrace/Wagtail dynamic templates
Created October 11, 2018 22:15
Show Gist options
  • Save bq1990/1bd8809bd64f882792c1fecaff7931c9 to your computer and use it in GitHub Desktop.
Save bq1990/1bd8809bd64f882792c1fecaff7931c9 to your computer and use it in GitHub Desktop.
Override Wagtail CMS templates based on the URL of the incoming request. Search by specific URL, then look for templates which override by model type.
class PathOverrideable(object):
def get_template(self, request, mode='', **kwargs):
try:
return self._path_overrideable_template
except AttributeError:
if not self.url:
return get_template(self.template)
path = self.url.strip('/')
model_name = camelcase_to_underscore(self.specific_class.__name__)
if mode:
mode = ':'+mode
model_template = model_name + mode + '.html'
full_path = os.path.join('default', path+mode+'.html')
templates = [full_path]
logger.debug("Adding candidate template based on URL: %s", full_path)
previous_index = len(path)
while True:
previous_index = path.rfind('/', 0, previous_index)
if previous_index == -1:
break
candidate = os.path.join('default', path[0:previous_index+1], model_template)
templates.append(candidate)
logger.debug("Adding candidate template for path-based model override: %s", candidate)
#templates.append("%s/%s" % (self.specific_class._meta.app_label, model_name))
templates.append(self.template) # add the default template as the last one to seek
logger.debug("Adding candidate template based on model name only: %s", self.template)
selected_template = select_template(templates)
logger.debug("Selected template: %s", selected_template.name)
self._path_overrideable_template = selected_template
return self._path_overrideable_template
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment