Tags are a great way to separate your content into different categories and make it easier for your visitors to find the articles and pages they are looking for.
A very basic tags field definition looks like this:
This creates a tags field where users can add any tags they want. You can finetune this setup with options, e.g. to limit the number of tags, allow only predefines options etc.
In the content file, the tags are stored as a comma separated list:
In your controllers, templates etc. you can now use the content of this field to filter your pages. Using the
filterBy() method we can not only filter pages by a single value single value in a field but also to find a certain value in a list like the tags list above. Therefore, we we can filter a set of pages by tag in a single line:
This will search through all children of the current page and return all pages with the tag "design". The third argument of the method tells it to search in a comma separated list. If you prefer to separate your tags with any other character, you are free to do that and specify that separation character as the third argument.
If we fetch the latest articles in our
blog.php template like this:
We can now filter them by a specific tag like this:
Of course, we usually don't want to filter by a hardcoded tag, but to have different URLs for each tag filter and use this parameter to filter our article list. So that an URL like
http://yourdomain.com/blog/tag:fun would show all articles that are tagged fun and
http://yourdomain.com/blog/tag:design all design articles.
param() helper function, we can fetch those parameters passed by the URL:
Note that you have to use a semicolon instead of a colon on Windows systems. In your code, you can use the
kirby\http\params::separator() method to make sure that the resulting URL is compatible with both Linux and Windows servers.
We can now replace
'design' in our articles example above with the param function.
We are almost there, but we want to make sure that the filter is only applied when a tag is added to the URL. We need an if clause to do that:
We are now ready to filter all your articles in our blog by specifying the tag in the URL
To fetch all tags for a tagcloud we can use the pluck method, which will extract the values of a single field into an array.
Putting it all together in
/controllers/blog.php makes it easier to keep the blog template clean.
Once we've done that, the
blog.php template is free of any logic, which makes it much more readable and easier to maintain. The template will automatically know the passed variables ($articles, $pagination, $tags & $tag)