Display model data on a cms page
8
There are many ways to display a model's data on a cms page. This trick describes two:
Via page execution lifecycle
url = "/blog/:slug"
==
use Acme\Blog\Models\Post;
function onStart()
{
$this['post'] = Post::where('slug', $this->param('slug'))->first();
}
==
<h2>{{ post.title }}</h2>
<div>{{ post.content }}</div>
Via a custom component
Register your custom component in your Plugin.php.
// Plugin.php
public function registerComponents()
{
return [
Acme\Blog\Components\BlogDetail::class => 'blogDetail',
];
}
Create the blogDetail
component as components/BlogDetail.php
namespace Acme\Blog\Components;
use Cms\Classes\ComponentBase;
class BlogDetail extends ComponentBase
{
public $blog;
public function defineProperties()
{
return [
'slug' => [
'type' => 'string',
'title' => 'Slug',
]
];
}
public function onRun()
{
$this->blog = $this->page['blog'] = Post::where('slug', $this->property('slug'))->first();
}
}
Finally, place the component on your CMS page.
url = "/blog/:slug"
[blogDetail]
slug = "{{ :slug }}"
==
<h2>{{ blogDetail.post.title }}</h2>
<div>{{ blogDetail.post.content }}</div>
{# Since we set $this->page['blog'] the post is also available
via the {{ post }} variable directly.
@see https://octobertricks.com/tricks/access-component-properties-page-or-partial
#}
There are no comments yet
Be the first one to comment