Question

Stumped on this. I want to link my post tags so that when it's clicked it lists all post to that tag, similar to a tag cloud---adding that functionality to the individual tags under the post.

Currently, I have it set it up to use the same function as my tag cloud but when I hover over one tag it shows all tags as I've used the blog results (blog.tags) in the for loop. See screen shot: (hovering over one tag shows all tags in the blog post)

enter image description here

When I use a get all tags and a for loop through those it works (gives me all posts by tags when I select on a specific tag), but it also lists all the tags and not the ones specific to the post which I don't want. (tags are stored as strings) See in screen.

enter image description here

How do I set it up to where it only shows me the specific tag I'm hovering over and not all tags in the post?

Twig

{% for blog in pagination %}

<p>Tags: <span class="highlight"><a href="{{ path('AcmeDemoBundle_tag', { 'tag': blog.tags }) }}">{{ blog.tags }}</a></span></p><br><br>

{% endfor %}

Controller

public function indexAction($tag = null)
{
    // Search function using code from Services/Search.php
    $query = $this->get('search');
    $results = $query->search();

    $em = $this->getDoctrine()->getManager();

    $blogs = $em->getRepository('AcmeDemoBundle:Blog')
        ->getBlogs();

    // Get all tags
    $tags = $em->getRepository('AcmeDemoBundle:Blog')
        ->getTags();

    // Get all posts by tag   
    $postTags = $em->getRepository('AcmeDemoBundle:Blog')
        ->getPostsByTags($tag);

    $paginator  = $this->get('knp_paginator');
    $pagination = $paginator->paginate(
        $blogs,
        $this->get('request')->query->get('page', 1)/*page number*/,
        5/*limit per page*/
    );

    return array(
        'blogs'      => $blogs,
        'query'      => $query,
        'results'    => $results,
        'tags'       => $tags,
        'postTags'   => $postTags,
        'pagination' => $pagination,
    );
}

public function tagAction($tag = null)
{
    $em = $this->getDoctrine()->getManager();

    $tags = $em->getRepository('AcmeDemoBundle:Blog')
        ->getPostsByTags($tag);

    if (!$tags) {
        throw $this->createNotFoundException('Unable to find blog posts');
    }

    return array(
        'tags' => $tags,
    );
}
Was it helpful?

Solution

Noticed the code you use:

{% for blog in pagination %}

Tags: {{ blog.tags }}



{% endfor %} It is not a recommended way.

The correct way is you have to use a nested loop and the tag links should be presented something like:

tag1 tag2 ...

It is never a good idea to store all the tags in just one field and separated with comma or whatever:

Book1 | tag1, tag2, tag3,...

But it is recommended to do like this:

Book1 | tag1 Book2 | tag2 ...

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top