[英]How can I show a list of comma-separated related model titles using Phalcon's Volt templates?
I want to display a list of related models in my view, as a comma-separated list. 我想在我的视图中显示相关模型的列表,以逗号分隔的列表。
Say I have a Posts model, and related Tags, post.getTags()
gets the related models but I can't see how to then concatenate them in a way that will produce the right output. 假设我有一个Posts模型和相关的Tag,
post.getTags()
获取相关的模型,但是我看不到如何以可以产生正确输出的方式将它们串联起来。
In plain PHP views, I'd simply put the HTML into an array and implode(', ', $tagLinks)
. 在普通的PHP视图中,我只是将HTML放入数组并
implode(', ', $tagLinks)
。
How can I achieve the same output with Volt? 如何用Volt实现相同的输出?
Create a filter inside your volt engine. 在电压引擎内创建一个过滤器。
$compiler = $volt->getCompiler();
$compiler->addFilter('joiner', function($resolvedArgs, $exprArgs) {
$text = 'implode(", ", ' . $resolvedArgs . ')';
return $text;
});
and use that 'joiner' filter inside your template. 并在模板中使用该“联接”过滤器。
{{ post.getTags() | joiner }}
finally. 最后。 if you too lazy to create a filter or function then just type php code.
如果您懒于创建过滤器或函数,则只需键入php代码。 it's work on volt.
它在伏特上工作。
some tags : <?= implode(', ', $tagLinks) ?>
Edit: I think volt already have join
filter . 编辑:我认为伏特已经有
join
过滤器。 see http://docs.phalconphp.com/en/latest/reference/volt.html#filters 参见http://docs.phalconphp.com/en/latest/reference/volt.html#filters
Seeing as I wanted to get formatted information from a model, I couldn't just use a plain implode() or join filter. 看到我想从模型中获取格式化信息,我不能只使用普通的implode()或联接过滤器。 As suggested by Eugene, I added a custom function to the Volt engine, and a method to my Model to get the correctly-formatted info.
根据Eugene的建议,我向Volt引擎添加了一个自定义函数,并为我的模型添加了一种方法,以获取格式正确的信息。
Custom Volt function (in an App\\Formatter class I'd already got for other view-related formatting): 自定义Volt函数(在App \\ Formatter类中,我已经获得了用于其他与视图相关的格式的信息):
static public function joinModels($resultset, $function, $join = ', ')
{
$result = '';
foreach ($resultset as $item) {
$result .= $item->$function() . $join;
}
return substr($result, 0, strlen($join) * -1);
}
Added it to Volt: 将其添加到伏特:
$compiler = $volt->getCompiler();
$compiler->addFunction('joinModels', 'App\\Formatter::joinModels');
And in the Model: 在模型中:
public function linkTo()
{
return Phalcon\Tag::linkTo('tags/' . urlencode($this->name), htmlspecialchars($this->name));
}
Then, finally, in my view: 然后,最后,在我看来:
{% set postTags = post.getTags() %}
{% if postTags.count() %}
{{ joinModels(postTags, 'linkTo') }}
{% else %}
None
{% endif %}
Many thanks to those that answered for the help. 非常感谢那些回答了我们的帮助。
已经有连接过滤器: {{ tagLinks|join(",") }}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.