如何在Twig中显示类型名称

时间:2019-05-13 10:38:41

标签: symfony twig

我有2个表: Product Type 。关系是一种类型具有许多 Product

Type:    id, name
Product: id, name, type_id

我不知道如何在Twig中显示类型名称,我是Symfony的新手,这是我的代码:

<div>
    {% for pro in product %}
        <div>Product name: {{ pro.name }}</div>
        <div>
            Type name:
        </div>
        <div>Price: {{ pro.price }}</div>
        <div>
            {% for img in pro.images %}
                <img src="{{ "/uploads/product/" ~ img.path }}" style="height: 100px;">
            {% endfor %}
        </div>
    {% endfor %}
</div>

2 个答案:

答案 0 :(得分:3)

您可以在Twig中访问对象的属性。您不应查看数据库,而应查看实体的创建方式。您的产品具有$id$name$type Type 具有$id$name

  • 在Twig中,您可以{{product.name}}
  • 要获取类型,您需要{{product.type}}
  • 要获取类型的名称,您需要{{product.type.name}}

因此,在您的代码中,将是:

<div>
    Type name: {{ pro.type.name }} 
</div>

在内部,当您执行$product时,Twig解析器将获取getName()并检查其是否具有方法{{product.name}}。相同的逻辑适用于{{product.type.name}}。它检查$product是否有getType(),然后检查是否有getName()。 PHP等效项为$product->getType()->getName()

几乎永远不要在代码中键入实际的方法。如果有必要,您可能需要退后一步并重新评估,因为它通常是code smell

答案 1 :(得分:2)

您只需在代码中添加{{pro.type.name}}:

<div>
    {% for pro in product %}
        <div>Product name: {{ pro.name }}</div>
        <div>
            Type name: {{ pro.type.name }}
        </div>
        <div>Price: {{ pro.price }}</div>
        <div>
            {% for img in pro.images %}
                <img src="{{ "/uploads/product/" ~ img.path }}" style="height: 100px;">
            {% endfor %}
        </div>
    {% endfor %}
</div>

并确保type属性引用Type实体。您的产品实体应具有如下的type属性:

/**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Type", inversedBy="products")
     * @ORM\JoinColumn(nullable=false)
     */
    private $type;

 // getter

public function getType()
    {
        return $this->type;
    }

您的Type实体应具有如下的product属性:

/**
     * @ORM\OneToMany(targetEntity="AppBundle\Entity\Type", mappedBy="type")
     * @ORM\JoinColumn(nullable=true)
     */
    private $products;

public function getProducts()
    {
        return $this->products;
    }