-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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