【问题标题】:Symfony2/Doctrine - How to select a single tag from a blog.tags propertySymfony2/Doctrine - 如何从 blog.tags 属性中选择单个标签
【发布时间】:2014-04-22 03:09:49
【问题描述】:

如何从 blog.tags 中选择单个标签?我正在尝试从 blog.tags 属性链接单个标签。现在,当我将鼠标悬停在单个标签上时,我会看到一组标签,而不是单个标签。

标签

将鼠标悬停在一个标签上时的一组标签:

我正在为所有博客使用 for 循环,它是 twig 文件中的属性。我需要能够在 blog.tags 字段中的每个标签上进行选择以链接它,我该如何设置?

树枝文件

{% for blog in pagination %}
 {% for tag in blog.tagsArray %}
   <p>Tags: <span class="highlight"><a href="{{ path('AcmeDemoBundle_tag', { 'tag': tag }) }}">{{ tag }}</a></span></p><br><br>
 {% endfor %}    
{% endfor %}

实体

/**
 * @var string
 *
 * @ORM\Column(name="tags", type="text")
 */
private $tags;

/**
 * Set tags
 *
 * @param string $tags
 * @return Blog
 */
public function setTags($tags)
{
    $this->tags = $tags;

    return $this;
}

/**
 * Get tags
 *
 * @return string
 */
public function getTags()
{
    return $this->tags;
}

控制器

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

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

    $tags = $em->getRepository('LSHealthFitnessBundle:Blog')
        ->getTags();

    $postTags = $em->getRepository('LSHealthFitnessBundle: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,
        'tags'       => $tags,
        'postTags'   => $postTags,
        'pagination' => $pagination,
    );
}

列表格式:(每个答案响应)

【问题讨论】:

    标签: symfony tags doctrine twig


    【解决方案1】:

    你应该在你的树枝模板中写第二个 for 循环,像这样:

    {% for blog in pagination %}
        {% for tag in blog.tagsArray %}
            <a href="{{ path('AcmeDemoBundle_tag', { 'tag': tag }) }}">{{ tag }}</a>&nbsp;
        {% endfor %}
        <br/>
    {% endfor %}
    

    这将为每个博客创建一个标签列表(每个在单独的行中)

    [编辑]:

    将这样的内容添加到您的博客实体中:

    public function getTagsArray()
    {
        return explode(',' ,$this->tags);
    }
    

    这会将标签字符串转换为数组(以逗号分隔)。然后你可以通过在 twig 中调用blog.tagsArray 来获取标签数组。我已经更新了上面的代码。

    【讨论】:

    • 嗯,尝试这个让我的整个评论行消失了?
    • 我认为博客和标签之间存在多对多关系。答案已更新。
    • 好的,cmets 回来了,但它以列表格式垂直列出(标签:ex1,下一行,标签:ex2 等)不像原来的一行。标签:ex1、ex2、ex 3等
    • 有什么办法可以改变它,使它不在单独的行上?所以它只是标签:Ex1、Ex2、Ex3 等。但它仍然可以选择?
    • 您是否在树枝上添加了第二个循环?你能更新你的模板代码吗?
    猜你喜欢
    • 1970-01-01
    • 2013-07-08
    • 2018-05-28
    • 2011-02-17
    • 1970-01-01
    • 2013-08-22
    • 1970-01-01
    • 2015-11-06
    • 2012-06-29
    相关资源
    最近更新 更多