Skip to content

Commit e68f19b

Browse files
committed
template_name can be a list of templates passed to loader.select_template. Thanks to zifot for the suggestion.
1 parent f16767c commit e68f19b

File tree

4 files changed

+20
-3
lines changed

4 files changed

+20
-3
lines changed

haystack/fields.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -119,11 +119,14 @@ def prepare_template(self, obj):
119119
raise SearchFieldError("This field requires either its instance_name variable to be populated or an explicit template_name in order to load the correct template.")
120120

121121
if self.template_name is not None:
122-
template_name = self.template_name
122+
template_names = self.template_name
123+
124+
if not isinstance(template_names, (list, tuple)):
125+
template_names = [template_names]
123126
else:
124-
template_name = 'search/indexes/%s/%s_%s.txt' % (obj._meta.app_label, obj._meta.module_name, self.instance_name)
127+
template_names = ['search/indexes/%s/%s_%s.txt' % (obj._meta.app_label, obj._meta.module_name, self.instance_name)]
125128

126-
t = loader.get_template(template_name)
129+
t = loader.select_template(template_names)
127130
return t.render(Context({'object': obj}))
128131

129132
def convert(self, value):
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
BAR!
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
FOO!

tests/core/tests/fields.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,10 @@ def test_init(self):
232232

233233
foo = CharField(use_template=True, template_name='foo.txt')
234234
self.assertEqual(foo.template_name, 'foo.txt')
235+
236+
# Test the select_template usage.
237+
foo = CharField(use_template=True, template_name=['bar.txt', 'foo.txt'])
238+
self.assertEqual(foo.template_name, ['bar.txt', 'foo.txt'])
235239

236240
def test_prepare(self):
237241
mock = MockModel()
@@ -248,6 +252,14 @@ def test_prepare(self):
248252
template3 = CharField(use_template=True)
249253
template3.instance_name = 'template'
250254
self.assertEqual(template3.prepare(mock), u'Indexed!\n1')
255+
256+
template4 = CharField(use_template=True, template_name='search/indexes/foo.txt')
257+
template4.instance_name = 'template'
258+
self.assertEqual(template4.prepare(mock), u'FOO!\n')
259+
260+
template5 = CharField(use_template=True, template_name=['foo.txt', 'search/indexes/bar.txt'])
261+
template5.instance_name = 'template'
262+
self.assertEqual(template5.prepare(mock), u'BAR!\n')
251263

252264

253265
##############################################################################

0 commit comments

Comments
 (0)