How can I show a list of comma-separated related model titles using Phalcon's Volt templates?

StackOverflow https://stackoverflow.com/questions/18806535

  •  28-06-2022
  •  | 
  •  

Question

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?

Was it helpful?

Solution 2

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.

OTHER TIPS

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

There is join filter already: {{ tagLinks|join(",") }}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top