从标签数组创建指向标签列表的链接

Create links to tagged list from an array of tags

我刚刚学习了标签教程 (https://book.cakephp.org/3.0/en/tutorials-and-examples/cms/tags-and-users.html) on the Red Velvet Cookbook. I was successful in adding tagging to my website. Though I feel it needs a couple more things. The comma separated list of tags is just that, a list. I would prefer a list of links. The links would obviously link to a list of posts that are tagged with the same tag. This list already exists thanks to the tutorial. The url looks like http://localhost:8765/story/tagged/cats/

我已经摆弄过 html 帮助程序来尝试创建链接,但我不确定如何使用数组执行此操作。任何线索或帮助将不胜感激。

这是我模板中显示标签列表的行

<p><b>Tags:</b> <?= h($story->tag_string) ?></p>

这是获取 tag_string

的函数
class Story extends Entity
{

/**
 * Fields that can be mass assigned using newEntity() or patchEntity().
 *
 * Note that when '*' is set to true, this allows all unspecified fields to
 * be mass assigned. For security purposes, it is advised to set '*' to false
 * (or remove it), and explicitly make individual fields accessible as needed.
 *
 * @var array
 */
protected $_accessible = [
    '*' => false,
    'tag_string' => true
];

protected function _getTagString()
{
    if (isset($this->_properties['tag_string'])) {
        return $this->_properties['tag_string'];
    }
    if (empty($this->tags)) {
        return '';
    }
    $tags = new Collection($this->tags);
    $str = $tags->reduce(function ($string, $tag) {
        return $string . $tag->name . ', ';
    }, '');
    return trim($str, ', ');
}

}

在您的 $story 实体中,您有 tags 属性,您已经在计算字段 tag_string 中使用了它。要获得分离的标签,您需要在模板中对其进行迭代,例如:

<ul>
<?php foreach($story->tags as $tag): ?>
    <li><?= $tag->title ?></li>
<?php endforeach; ?>
</ul>

假设您的 StoriesController 中有一个名为 tagged 的方法,它接受一个参数:标签标题,您可以为每个标签使用 HtmlHelper 构造 link:

<ul>
<?php foreach($story->tags as $tag): ?>
    <li>
        <?= $this->Html->link($tag->title, [
            "controller" => "Stories",
            "action" => "tagged",
            $tag->title
        ], [
            "class" => "your-tag-link-class" //second array is for properties, in case you would like to add eg class for these links to style them using css.
        ]) ?>
    </li>
<?php endforeach; ?>
</ul>