general: add support for varying cell template based on slug (#7141)

This commit is contained in:
Frédéric Péters 2016-09-29 15:30:03 +02:00
parent ae8f3eff56
commit 760c7a2487
3 changed files with 36 additions and 1 deletions

View File

@ -17,6 +17,7 @@
import feedparser
import hashlib
import json
import os
import requests
import subprocess
@ -429,7 +430,15 @@ class CellBase(models.Model):
def render(self, context):
context.update(self.get_cell_extra_context(context))
tmpl = template.loader.get_template(self.template_name)
template_names = ['combo/' + self._meta.model_name + '.html']
base_template_name = self._meta.model_name + '.html'
if self.template_name:
base_template_name = os.path.basename(self.template_name)
template_names.append(self.template_name)
if self.slug:
template_names.append('combo/cells/%s/%s' % (self.slug, base_template_name))
template_names.reverse()
tmpl = template.loader.select_template(template_names)
return tmpl.render(context)
def modify_global_context(self, context, request=None):

View File

@ -0,0 +1 @@
<div class="XXX">{{cell.text|safe}}</div>

View File

@ -1,7 +1,9 @@
import os
import pytest
from combo.data.models import Page, CellBase, TextCell, LinkCell
from django.forms.widgets import Media
from django.test import override_settings
pytestmark = pytest.mark.django_db
@ -90,3 +92,26 @@ def test_link_cell():
cell.link_page = None
cell.save()
assert cell.render(ctx).strip() == '<a href="http://example.net/#anchor">altertitle</a>'
def test_variant_templates():
page = Page(title='example page', slug='example-page')
page.save()
cell = TextCell()
cell.page = page
cell.text = '<p>foobar</p>'
cell.order = 0
cell.save()
from django.template import Context
ctx = Context()
assert cell.render(ctx).strip() == '<p>foobar</p>'
with override_settings(TEMPLATE_DIRS=['%s/templates-1' % os.path.abspath(os.path.dirname(__file__))]):
assert cell.render(ctx).strip() == '<p>foobar</p>'
cell.slug = 'foobar'
cell.save()
assert cell.render(ctx).strip() == '<div class="XXX"><p>foobar</p></div>'
assert cell.render(ctx).strip() == '<p>foobar</p>'