Rey*_*ier 22 symfony twig symfony-2.3
我在我的控制器中有一个函数返回实体数组,所以在我的twig模板中我这样做迭代元素:
{% for groupName, entity in items %}
<ul>
<ul>
{% for element in entity %}
<li>{{ element.getLabel }}</li>
<li><input type="text" name="detail[{{ element.getId }}]" id="pd_{{ element.getId }}" /><input type="text" name="price[{{ element.getId }}]" id="pd_price_{{ element.getId }}" /><input type="text" name="stock[{{ element.getId }}]" id="pd_stock_{{ element.getId }}" /></li>
{% endfor %}
</ul>
</ul>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
在我的控制器中我也有这个PHP函数:
private function DetailCombination($arr, $level, &$result, $curr = array()) {
for ($i = 0; $i < count($arr); $i++) {
$new = array_merge($curr, array($arr[$i]));
if ($level == 1) {
sort($new);
if (!in_array($new, $result)) {
$result[] = $new;
}
} else {
combinations($arr, $level - 1, $result, $new);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我可以这样称呼它:
for ($i = 0; $i < count($arr); $i++) {
$this->DetailCombination($arr, $i + 1, $result);
}
// TEST
foreach ($result as $arr) {
echo join(" ", $arr) . '<br>';
}
Run Code Online (Sandbox Code Playgroud)
可以从Twig模板访问PHP函数,以获得实体中所有可能的元素组合?怎么样?
**更新**
这是返回由Twig Template处理的实体的函数:
private function getVariations($category_id) {
$items = array();
$em = $this->getDoctrine()->getManager();
$entityCategory = $em->getRepository('CategoryBundle:Category')->find($category_id);
foreach ($entityCategory->getProductDetails() as $entity) {
if ($entity->getToProduct() == 1) {
foreach ($entity->getDetailGroup() as $group) {
if (!array_key_exists($group->getName(), $items)) {
$items [$group->getName()] = array();
}
$items [$group->getName()] [] = $entity;
}
}
}
return $items;
}
Run Code Online (Sandbox Code Playgroud)
cre*_*lem 20
它无法直接访问Twig中的任何PHP函数.
你可以做的是写一个Twig扩展.一个常见的结构是,使用一些实用程序函数编写服务,将Twig扩展名编写为桥,以便从twig访问服务.Twig扩展将使用该服务,您的控制器也可以使用该服务.
看看:http://symfony.com/doc/current/cookbook/templating/twig_extension.html
干杯.
ump*_*sky 10
已经有一个Twig扩展,允许您从Twig模板调用PHP函数,如:
Hi, I am unique: {{ uniqid() }}.
And {{ floor(7.7) }} is floor of 7.7.
Run Code Online (Sandbox Code Playgroud)
查看官方扩展库.
我很惊讶代码答案还没有发布,它是单行的。
你可以 {{ categeory_id | getVariations }}
这是一个
单线:Twig2:
$twig->addFilter('getVariations', new Twig_Filter_Function('getVariations'));
Run Code Online (Sandbox Code Playgroud)
树枝3:
$this->twig->addFilter(new \Twig\TwigFilter('getVariations','getVariations'));
Run Code Online (Sandbox Code Playgroud)
Twig 3 但作为函数而不是过滤器:
$this->twig->addFunction(new \Twig\TwigFunction('getVariantsFunc', 'getVariations'));
Run Code Online (Sandbox Code Playgroud)