我有一个数组包含与实体相关的静态数据Product:
public static $category = array(
1 => 'animal.png',
2 => 'blague.png',
3 => 'devinette.png',
4 => 'enfant.png',
5 => 'h-f.png',
6 => 'nationalite.png',
7 => 'politique.png',
8 => 'sport.png',
9 => 'name',
10 => 'travail.png',
11 => 'vulgaire.png',
12 => 'autre.png',
);
我应该在哪里声明数组?
我如何从 Twig 视图中获取数据?
Thanks
我不知道这是否是最好的方法,但我使用了与您的代码类似的方法:
class Product
{
protected static $category = array(
1 => 'animal.png',
2 => 'blague.png',
3 => 'devinette.png',
// ...
)
);
}
然后你可以在这个类中添加一些函数以便从数组中获取数据
public function getCategoryImageFromIndex($a)
{
return self::$category[$a];
}
// if you have a getter getCategory() which returns the category of the Product
public function getCategoryImage()
{
return self::$category[$this->getCategory()];
}
然后你可以从 Twig 调用这些函数:
{{ product.categoryImageFromIndex(1) }}
将显示:
动物.png
And
{{ product.categoryImage }}
将显示该类别中相应的图像。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)