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

科里·伍兹(Corey Woods)

我刚刚按照Red Velvet Cookbook上的标签教程(https://book.cakephp.org/3.0/en/tutorials-and-examples/cms/tags-and-users.html)进行操作。我成功地在网站上添加了标签。虽然我觉得它还需要几件事。用逗号分隔的标签列表就是列表。我希望有一个链接列表。这些链接显然将链接到使用相同标签标记的帖子列表。由于本教程,该列表已经存在。网址看起来像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>

假设您的StoriesControllernamed中有一个方法tagged,该方法接受一个参数:标记标题,则可HtmlHelper以为每个标记构建链接

<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>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章