Twig Collections Reference
The collection adapter provides access to collections and their objects, including listing, fetching, searching, URL generation, and navigation helpers.
Listing Collections
Section titled “Listing Collections”list()
Section titled “list()”Get all accessible collections (filtered by edition restrictions).
{% for col in cms.collection.list() %} <p>{{ col.name }} ({{ col.id }})</p>{% endfor %}byCategory()
Section titled “byCategory()”Get collections grouped by their category.
{% for category, collections in cms.collection.byCategory() %} <h3>{{ category }}</h3> {% for col in collections %} <p>{{ col.name }}</p> {% endfor %}{% endfor %}Get a single collection’s metadata. Returns an empty array if the collection is inaccessible.
{% set blog = cms.collection.get('blog') %}{% if blog %} <h1>{{ blog.name }}</h1> <p>{{ blog.description }}</p>{% endif %}objectCount()
Section titled “objectCount()”Get the number of objects in a collection using cached metadata. This is much more efficient than loading all objects and counting them.
<p>{{ cms.collection.objectCount('blog') }} blog posts</p><p>{{ cms.collection.objectCount('products') }} products</p>
{# Avoid this — loads entire index just to count #}{# {{ cms.collection.objects('blog')|length }} #}Fetching Objects
Section titled “Fetching Objects”objects()
Section titled “objects()”Get all objects from a collection. Takes the collection id and nothing else — to narrow the result, pipe it through the filterCollection and sorting filters.
Note: For a listing, prefer
query(). It takes the same filter and sort rules as options, returns only the page you show along with the numbers pagination needs, and caches that page until the collection is next saved.objects()loads the whole index on every request, which is fine for a small collection but slows down every page as the collection grows. Keepobjects()for when you really need every object, such as building a menu or grouping a small collection.
{% for post in cms.collection.objects('blog') %} <article> <h2>{{ post.title }}</h2> <p>{{ post.excerpt }}</p> </article>{% endfor %}objects() returns index data, not full records. Each entry holds only the properties listed in the schema’s index array (plus id). A property that is not indexed is simply absent from every entry, so post.body on a non-indexed body prints nothing rather than erroring. Either add the property to the schema’s index, or fetch the full record per object with object() when you need it:
{% for entry in cms.collection.objects('blog') %} {% set post = cms.collection.object('blog', entry.id) %} {{ post.body|raw }}{% endfor %}query()
Section titled “query()”Get one page of a collection, filtered and sorted. Use it instead of objects() piped through filters when a collection is large: the result is cached until the collection is next saved, so a repeat of the same query does not load the whole index again.
{% set result = cms.collection.query('blog', { filter: [ {property: 'draft', operator: 'isfalse'}, {property: 'category', value: 'news'} ], sort: 'date:desc', limit: 10, page: getData.page|default(1)}) %}
{% for post in result.objects %} <h2><a href="{{ cms.collection.objectUrl('blog', post) }}">{{ post.title }}</a></h2>{% endfor %}
{% if result.hasMore %} <a href="?page={{ result.page + 1 }}">Older posts</a>{% endif %}| Option | What it does |
|---|---|
search | Text to search for, matched as search() matches it: every word, or for any word, field:value for one field. Empty means no search, so a search page with no query lists everything. |
searchPriority | A field name or a list of them. A match in an earlier field comes first. Used only when there is no sort. |
filter | A list of rules, written exactly as for filterCollection. |
sort | A sort string such as 'date:desc,title:asc', or a list of rules as for sortCollection. |
limit | Objects per page. Leave it out to get every match. |
page | The page to return, starting at 1. Needs a limit. |
offset | The number of objects to skip, as an alternative to page. |
The result has objects (index data, like objects()), total (matches before paging), limit, offset, page, pages and hasMore.
A filter that depends on today’s date, such as past, today, thisMonth or before: 'now', is cached for one minute at most, so a scheduled post appears within a minute of its date.
The search runs first, then the filter, the sort and the page. So a search page can show only published posts, newest first, ten at a time:
{% set result = cms.collection.query('blog', { search: getData.q, searchPriority: ['title', 'summary'], filter: [{property: 'draft', operator: 'isfalse'}], limit: 10, page: getData.page|default(1)}) %}
<p>{{ result.total }} results</p>{% for post in result.objects %} <h2><a href="{{ cms.collection.objectUrl('blog', post) }}">{{ post.title }}</a></h2>{% endfor %}{{ cms.render.paginationFull(result.total, result.page, result.limit, 'page') }}The search text comes from visitors, so only the page is cached, and the text is made lowercase with single spaces and cut to 200 characters first. “Pasta ” and “pasta” share one cache entry.
object()
Section titled “object()”Get a single object by collection and ID. Returns the full record — every property, indexed or not — or an empty array if not found. password properties are never included: stored hashes do not reach templates.
{% set post = cms.collection.object('blog', 'my-post') %}{% if post %} <h1>{{ post.title }}</h1> {{ post.content|markdown }}{% endif %}property()
Section titled “property()”Get all unique values for a specific property across a collection. Useful for building filter lists.
{# Get all categories used in blog posts #}{% set categories = cms.collection.property('blog', 'category') %}<select> {% for cat in categories %} <option>{{ cat }}</option> {% endfor %}</select>
{# Get all tags #}{% set tags = cms.collection.property('blog', 'tags') %}Search
Section titled “Search”search()
Section titled “search()”Search every field of a collection for a query string and return all the matches. Every word must match, as a whole word; put or between words to match any of them, or write field:value to search one field. The properties you pass only order the results: a match in the first property comes first. For a search page, prefer query() with its search option, which pages the results and caches them.
{# Search a single property #}{% set results = cms.collection.search('blog', 'php tutorial', 'title') %}
{# Search multiple properties in priority order #}{% set results = cms.collection.search('blog', query, ['title', 'content', 'tags']) %}
{% for item in results %} <article> <h3>{{ item.title }}</h3> <p>{{ item.excerpt }}</p> </article>{% endfor %}| Parameter | Type | Description |
|---|---|---|
collection | string | Collection to search |
query | string | Search query string |
propertyPriorities | string|array | Property name or ordered array of properties. Matches in earlier properties come first. Every field is searched either way. |
searchScored()
Section titled “searchScored()”Relevance-ranked search: returns best-partial matches first, ranked by how many query terms each object matched (OR recall), instead of the all-or-nothing AND filter search() uses. Use it for descriptive, multi-word queries where returning the closest match beats returning nothing.
{% set results = cms.collection.searchScored('products', searchTerm) %}
{# Optional per-field weights (field => weight, default 1.0) boost important fields #}{% set results = cms.collection.searchScored('products', searchTerm, {'name': 3, 'tags': 2}) %}
{% for item in results %} <a href="{{ cms.collection.objectUrl('products', item) }}">{{ item.name }}</a>{% endfor %}Results are plain object arrays in ranked order — the same shape search() returns.
| Parameter | Type | Description |
|---|---|---|
collection | string | Collection to search |
query | string | Search query string |
weights | object | Optional per-field weights (field => weight); unlisted fields default to 1.0 |
Differences from search():
- Ranks by term coverage, not field position, and returns partial matches instead of requiring every term.
- Does not support
field:valuescoped queries or explicitand/oroperators — usesearch()for those. - Opt-in and additive;
cms.collection.search()is unchanged. See the relevance ranking notes.
URL Generation
Section titled “URL Generation”objectUrl()
Section titled “objectUrl()”Get the URL for an object. Supports templated URL patterns with object data.
{# By ID #}<a href="{{ cms.collection.objectUrl('blog', 'my-post') }}">Read More</a>
{# By object (recommended — avoids re-fetching for templated URLs) #}{% set post = cms.collection.object('blog', 'my-post') %}<a href="{{ cms.collection.objectUrl('blog', post) }}">{{ post.title }}</a>prettyUrl()
Section titled “prettyUrl()”Convert a URL path to a pretty URL (strips .php extension, adds trailing slash).
<a href="{{ cms.collection.prettyUrl('/blog/post.php') }}">Link</a>{# Outputs: /blog/post/ #}
{# With domain prefix #}<a href="{{ cms.collection.prettyUrl('/blog/post.php', true) }}">Full URL</a>{# Outputs: https://example.com/blog/post/ #}canonicalObjectUrl()
Section titled “canonicalObjectUrl()”Get the absolute canonical URL for an object (includes the full domain).
{% set post = cms.collection.object('blog', 'my-post') %}<link rel="canonical" href="{{ cms.collection.canonicalObjectUrl('blog', post) }}">hasTemplateUrl()
Section titled “hasTemplateUrl()”Check if a collection uses a templated URL pattern (e.g., /blog/{slug}/).
{% if cms.collection.hasTemplateUrl('blog') %} <p>This collection uses pretty URLs</p>{% endif %}urlTemplateFields()
Section titled “urlTemplateFields()”Get the list of field names used in a collection’s URL template.
{% set fields = cms.collection.urlTemplateFields('blog') %}{# e.g., ['category', 'slug'] for /blog/{category}/{slug}/ #}validateUrlTemplateFields()
Section titled “validateUrlTemplateFields()”Validate that URL template fields are properly configured in the schema.
{% set validation = cms.collection.validateUrlTemplateFields('blog') %}{% if validation.notIndexed|length > 0 %} <p>Warning: fields not indexed: {{ validation.notIndexed|join(', ') }}</p>{% endif %}{% if validation.notRequired|length > 0 %} <p>Warning: fields not required: {{ validation.notRequired|join(', ') }}</p>{% endif %}{% if validation.prettyUrlDisabled %} <p>Warning: pretty URLs are disabled</p>{% endif %}Returns: array with keys:
notIndexed— field names not marked as indexed in the schemanotRequired— field names not marked as requiredprettyUrlDisabled— whether pretty URLs are disabled for the collection
objectUrlHasEmptySegments()
Section titled “objectUrlHasEmptySegments()”Check if an object’s generated URL has empty segments due to missing template data.
{% set post = cms.collection.object('blog', 'my-post') %}{% if cms.collection.objectUrlHasEmptySegments('blog', post) %} <p>Warning: this object has incomplete URL data</p>{% endif %}Navigation
Section titled “Navigation”redirectIfNotFound()
Section titled “redirectIfNotFound()”Redirect to the 404 page if the provided object is empty or null. The visitor is sent to the 404 page’s own address with a 302 — the URL they typed is lost, and a crawler records a redirect rather than a missing page. On a Site Builder site, prefer cms.notFound(), which renders the 404 page in place with a real 404 status.
{% set post = cms.collection.object('blog', id) %}{{ cms.collection.redirectIfNotFound(post) }}
{# With custom redirect URL #}{{ cms.collection.redirectIfNotFound(post, '/blog') }}
<h1>{{ post.title }}</h1>| Parameter | Type | Default | Description |
|---|---|---|---|
object | array|string|null | [] | Object to check |
redirectUrl | string | '' | Custom redirect URL (default: 404 page) |
redirectToCanonicalUrl()
Section titled “redirectToCanonicalUrl()”Redirect to the canonical URL if the current URL doesn’t match. Supports multiple redirect methods.
{# Header redirect (default, recommended) #}{{ cms.collection.redirectToCanonicalUrl('blog', post) }}
{# Meta refresh redirect #}{{ cms.collection.redirectToCanonicalUrl('blog', post, 'meta') }}
{# JavaScript redirect #}{{ cms.collection.redirectToCanonicalUrl('blog', post, 'js') }}
{# Custom HTTP status code #}{{ cms.collection.redirectToCanonicalUrl('blog', post, 'header', 302) }}| Parameter | Type | Default | Description |
|---|---|---|---|
collectionId | string | required | Collection identifier |
idOrObject | string|array | required | Object ID or full object data |
method | string | 'header' | Redirect method: header, meta, js |
httpStatus | int | 301 | HTTP status code for header redirects |