# 为你的站点添加搜索
用 Wagtail 的 `start` 命令启动项目时,你会得到一个内置的搜索应用。这个内置的搜索应用为你的站点提供了简单的搜索功能。
不过,你可以自定义搜索模板,让它适配你的作品集站点。要自定义搜索模板,请打开 `search/templates/search/search.html` 文件并修改如下:
```html+django
{% extends "base.html" %}
{% load static wagtailcore_tags %}
{% block body_class %}template-searchresults{% endblock %}
{% block title %}Search{% endblock %}
{% block content %}
Search
{% if search_results %}
{# 添加这一段,用来显示找到的结果详情: #}
You searched{% if search_query %} for “{{ search_query }}”{% endif %}, {{ search_results.paginator.count }} result{{ search_results.paginator.count|pluralize }} found.
{# 把 HTML 元素换成 HTML 元素: #}
{% for result in search_results %}
-
{% if result.search_description %}
{{ result.search_description }}
{% endif %}
{% endfor %}
{# 通过添加以下内容来改进分页: #}
{% if search_results.paginator.num_pages > 1 %}
Page {{ search_results.number }} of {{ search_results.paginator.num_pages }}, showing {{ search_results|length }} result{{ search_results|pluralize }} out of {{ search_results.paginator.count }}
{% endif %}
{% if search_results.has_previous %}
Previous
{% endif %}
{% if search_results.has_next %}
Next
{% endif %}
{% elif search_query %}
No results found
{% endif %}
{% endblock %}
```
现在,我们来解释一下你在上面的模板中做的自定义:
1. 你用 `You searched{% if search_query %} for “{{ search_query }}”{% endif %}, {{ search_results.paginator.count }} result{{ search_results.paginator.count|pluralize }} found.
` 来显示搜索词以及找到的结果数量。如果找到多个搜索结果,你还用它来显示“result”的复数形式。
2. 你把 `` HTML 元素换成了 `` HTML 元素。`` HTML 元素内含一个循环,遍历每个搜索结果并把它们显示为列表项。使用 `` 可以让你得到带编号的搜索结果。
3. 你改进了模板中的分页。`{% if search_results.paginator.num_pages > 1 %}` 检查搜索结果是否超过一页。如果超过一页,它就显示当前页码、总页数、当前页的结果数量以及结果总数。`{% if search_results.has_previous %} and {% if search_results.has_next %}` 检查是否存在上一页和下一页搜索结果。如果存在,它就显示“Previous”和“Next”链接,并配上用于分页的相应 URL。
现在,你希望在站点的各处都能显示搜索入口。一种做法是把它加到页头。打开 `mysite/templates/includes/header.html` 文件并修改如下:
```html+django
{% load wagtailcore_tags navigation_tags wagtailuserbar %}
```
现在你就能执行搜索并查看结果了。不过,目前的搜索只会返回页面标题中出现的词。要让其他字段也能被搜索,必须把它们加入搜索索引 —— 参见 [](wagtailsearch_indexing)。在 `blog/models.py` 中加入下面的代码:
```python
# 加入现有的导入:
from wagtail.search import index
class BlogPage(Page):
# 保留现有的 parent_page_types、字段、方法和 content_panels 定义,并添加:
search_fields = Page.search_fields + [
index.SearchField("intro"),
index.SearchField("body"),
]
```
现在运行以下命令重建搜索索引,这次会把 `BlogPage` 的 `body` 字段包含进去:
```sh
python manage.py update_index
```
现在搜索就会返回正文文本中出现的词了。
干得好!你现在有了一个可完整部署的作品集站点。本教程的下一节会带你走完部署站点的流程。