Haystack搜索结果:如何在page.object_list中为不同模型使用不同模板?
我正在使用 Haystack 和 Solr 后端向现有 Django 站点添加搜索。我希望我的搜索能够跨多个不同的模型运行,并返回一组结果。
迭代结果时,我想根据每个结果的模型类型来格式化每个结果 - 例如,如果结果是 Apple,则使用一个结果模板,但如果结果是 Orange,则使用不同的模板。
到目前为止,我只是使用示例 搜索模板 的稍微修改版本。在模板中,结果出现在 page.object_list 中:
{% if page.object_list %}
<ul>
{% for result in page.object_list %}
<li>
{% if (isinstance(result.object, Apple)) %}
Apple: {{ result.object.titlefield_for_apple }}
{% else %}
Orange: {{ result.object.otherfield_for_orange }}
{% endif %}
</li>
{% endfor %}
</ul>
{% else %}
<p>No results found.</p>
{% endif %}
这不起作用,显然是因为 isinstance() 在模板中不可用。那么,如何根据对象的 Model 类型来控制模板逻辑呢?我可以在模板中使用另一个函数来执行相同的操作吗?
我想我可以测试对象的各个字段(if result.object.otherfield_for_orange
)来识别它,但这似乎不太优雅。我打赌这可以通过自定义模板标签来完成,但我对此没有经验。
I'm adding search to an existing Django site, using Haystack with a Solr backend. I want my search to work across several different models, and return a single set of of results.
When iterating through the results, I would like to format each result based on what model type it is -- e.g. if the result is an Apple, use one result template, but if it's an Orange, use a different template.
So far, I'm just using a slightly modified version of the example search template. In the template, the results come in page.object_list:
{% if page.object_list %}
<ul>
{% for result in page.object_list %}
<li>
{% if (isinstance(result.object, Apple)) %}
Apple: {{ result.object.titlefield_for_apple }}
{% else %}
Orange: {{ result.object.otherfield_for_orange }}
{% endif %}
</li>
{% endfor %}
</ul>
{% else %}
<p>No results found.</p>
{% endif %}
This doesn't work, apparently because isinstance() isn't available inside a template. So, how can I control template logic based on the the Model type of an object? Is there another function that I can use inside a template which does the same thing?
I suppose I could test various fields of the object (if result.object.otherfield_for_orange
) to identify it, but that seems inelegant. I bet this could be done with custom template tags, but I've no experience with those.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,呃,在问完这个问题后,我立即深入研究了 Haystack 文档,并找到了我所需要的:
这完全有道理,因为 Haystack 当然应该将类型与结果一起传回。它实际上传递了类型信息的多个版本,以便于在模板中使用:
Ok, duh, immediately after asking this I dug deeper into the Haystack docs, and found exactly what I need:
Which totally makes sense, because of course Haystack should pass the types back with the results. It actually passes several versions of the type info, for easy use in the template: