这个 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 其值为 蓝色 的条目,请使用 where 查询方法。使用 {% set %} Twig 标签会将结果分配给一个新变量。
{% set bluePosts = posts.where('color', 'blue').get() %}要仅显示具有关联作者的帖子,您可以使用 whereRelation 查询方法。要完成查询,请使用 get() 方法。以下列出了分配给 author 的帖子,其 slug 设置为 bella-vista。
{% 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。
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 %}