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.
In plain PHP views, I'd simply put the HTML into an array and implode(', ', $tagLinks)
.
How can I achieve the same output with 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. it's work on volt.
some tags : <?= implode(', ', $tagLinks) ?>
Edit: I think volt already have join
filter . see 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. 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.
Custom Volt function (in an App\\Formatter class I'd already got for other view-related formatting):
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(",") }}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.