【问题标题】:clickable tags in posts - Laravel帖子中的可点击标签 - Laravel
【发布时间】:2018-07-13 23:31:39
【问题描述】:

代码读取帖子中的主题标签并将它们保存在数据库中。

if($post)
    {
        preg_match_all('/#(\w+)/', $request->get('body'),$tagNames);
        // $tagnames contains an array of results. $tagnames[0] is all matches
        $tagIds = [];
        foreach($tagNames[0] as $tagName)
        {
            //$post->tags()->create(['name'=>$tagName]);
            //Or to take care of avoiding duplication of Tag
            //you could substitute the above line as
            $tag = Tag::firstOrCreate(['name'=>$tagName]);
            if($tag)
            {
                $tagIds[] = $tag->id;
            }

        }
        $post->tags()->sync($tagIds);
    }

现在我想让帖子中的标签可点击。这怎么可能?可以在 /tags/id 下调用来自标签的视图。

【问题讨论】:

    标签: laravel url routes tags hashtag


    【解决方案1】:

    创建href基于标签id的锚元素。几个例子:

    // loop the tags
    @foreach ($post->tags as $tag)
        <a href="{{ url(sprintf('tags/%d', $tag->id)) }}">I'm a tag link</a>
    @endforeach
    
    // or directly access the first one
    <a href="{{ url(sprintf('tags/%d', $post->tags->first()->id)) }}">I'm a tag link</a>
    

    更新

    在将帖子发送到视图之前处理帖子,将#username 文本替换为相应的标签。

    $postall = $user->posts()->with('comments')->where('status', 1)->latest()->get();
    
    $postall = $postall->map(function ($post, $key) {
        // $post->tags->pluck('name') is an array of #replaceme strings. example: ['#bill', '#joe', '#sally'] 
        // $links is an array of <a href="..">...</a>
    
        $links = $post->tags->map(function ($tag, $key) {
            return sprintf('<a href="/tags/%d">%s</a>', $tag->id, $tag->name);
        });
        return str_replace($post->tags->pluck('name'), $links, $post)
    });
    
    return return view('profiles.profile', compact('postall', 'followers', 'followings'));
    

    那么在你看来:{!! $post !!}

    但请注意用户输入的数据,并采取任何必要的预防措施来防止 sql 注入。

    【讨论】:

    • 谢谢,这是个好主意。但是标签应该直接链接到文本中,而不是文本之外。示例:我的名字是 #tom 而不是 #kevin
    • 你怎么知道标签在文本中的位置?您是否有占位符或某种标记来指示在何处放置链接?
    • 标签用 # 标记。正如您在上面的代码中看到的那样,所有单词都在单词之前用# 作为标记保存。
    • 您是否将$request-&gt;get('body') 存储在您的数据库中?
    • 正文存储在数据库中的“post”表中。以及具有多对可能关系的额外表中的标签
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 2018-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多