该 collection 组件在页面上显示一组条目。该 collection 组件可用于任何页面、布局或局部模板。
该组件支持以下属性。
| Property | Description |
|---|---|
| handle | The handle of the entry blueprint. |
| recordsPerPage | Number of records to display on a single page. Leave empty to disable pagination. |
| pageNumber | This value is used to determine what page the user is on. |
| sortColumn | Column name the records should be ordered by. |
| sortDirection | Direction the records should be ordered by. Supported values are asc and desc. |
以下将一组 Blog\Post 条目添加到页面。该集合在 Twig 中通过循环默认的 collection 变量来访问。
[collection]
handle = "Blog\Post"{% for post in collection %}
<h1>{{ post.title }}</h1>
{% endfor %}当同一页面上使用多个集合时,该组件可以使用组件别名被赋予名称 posts 而这正是页面可用的变量名。以下集合改为使用 posts 变量进行访问。
[collection posts]
handle = "Blog\Post"{% for post in posts %}
<h1>{{ post.title }}</h1>
{% endfor %}使用 is empty 或 is not empty 表达式来检查集合中是否至少有一个记录可供显示。
{% if posts is not empty %}
{# ... #}
{% endif %}当使用方法访问组件变量时,它将切换到数据库模型查询。例如,要只显示color字段值为blue的条目,请使用where查询方法。使用{% set %} Twig 标签将结果分配给一个新变量。
{% set bluePosts = posts.where('color', 'blue').get() %}若要仅显示具有相关作者的帖子,可以使用 whereRelation 查询方法。若要完成查询,请使用 get() 方法。以下列出了分配给 slug 设置为 bella-vista 的 author 的帖子。
{% set authorPosts = posts.whereRelation('author', 'slug', 'bella-vista').get() %}要根据记录的条目类型进行筛选,请使用 content_group 属性执行 where() 查询。 以下将列出使用条目类型代码 featured_post 的帖子。
{% set featuredPosts = posts.where('content_group', 'featured_post').get() %}您也可以改用 paginate() 方法对集合应用分页。
以下内容将对文章进行分页,每页 10 篇,并显示分页导航。
{% set authorPosts = posts.whereRelation(...).paginate(10) %}
{{ pager(authorPosts) }}请参阅分页功能以了解有关记录分页的更多信息。
:::
要搜索记录,使用 searchWhere() 方法 针对某一列的值执行搜索查询。 以下将使用所提供的术语和列,通过不区分大小写的查询来搜索记录。
{% set foundPages = pages.searchWhere(searchTerm, ['title', 'content']).get() %}您还可以使用 searchWhereRelation() 方法 来搜索相关记录,其中关系名称包含在该方法中,用于查询关系是否存在。
{% set foundPages = pages.searchWhereRelation(searchTerm, 'author', ['title']).get() %}在某些情况下,出于性能原因,您可能希望预加载相关记录。在集合上使用 load 方法,并传入关系名称。在下一个示例中,categories 关系将随集合中的每个帖子一起加载。
{% do authorPosts.load('categories') %}假设你想展示一个博客分类列表并统计每个分类下的文章数量。首先,定义逆向关系在分类蓝图上作为文章。
posts:
type: entries
source: Blog\Post
inverse: categories
hidden: true然后,在集合组件上调用 withCount 函数,接着调用 get 以返回分类记录的集合。这将在每个分类上创建一个名为 post_count 的属性。
{% set categories = collection.withCount('posts').get() %}
{% for category in categories %}
<h5>{{ category.title }} ({{ category.post_count }} posts)</h5>
{% endfor %}