October CMS resources and help articles

Simple and to the point. Optimized by the community.

Generate a link to a CMS page

4
by OFFLINE, last modified on February 10th, 2021

If you've got the following cms page called blog-post.htm in your theme...

title = "Blog post"
url = "/blog/:slug"
layout = "default"
is_hidden = 0

[blogPost]
==
{% component 'blogPost' %}

... you can use the following methods to generate a link to it:

In Twig

Pass the name of the cms page file to the page filter. Optionally pass along any URL parameters.

{# Example with parameters #}
{{ 'blog-post' | page({slug: 'a-slug-of-the-post'}) }}

{# Example without parameters #}
{{ 'blog' | page }}

{# Note: If you are linking to a RainLab.Pages page, use the staticPage filter #}
{{ 'static-blog' | staticPage }}

In PHP

Use the \Cms\Classes\Controller class to generate the URL.

// In a page or component context you can access the 
// controller via $this->controller
$this->controller->pageUrl('blog-post', ['slug' => 'a-slug-of-the-post']);
// If you don't have access to a controller you can
// easily create a new instance on the fly.
$url = (new \Cms\Classes\Controller)->pageUrl('blog-post', ['slug' => 'a-slug-of-the-post']);
// Or use the Page class helper
\Cms\Classes\Page::url('blog-post', ['slug' => 'a-slug-of-the-post'])

Discussion

1 comment

2
alxy
Post on March 1st, 2019 4:19 PM

A bit more readable is this method: https://github.com/octobercms/october/blob/master/modules/cms/classes/Page.php#L121

It then reads like this: Page::url('blog-post', ['slug' => 'a-slug-of-the-post'])

We use cookies to measure the performance of this website. Do you want to accept these cookies?