[英]How can I show a list of comma-separated related model titles using Phalcon's Volt templates?
我想在我的視圖中顯示相關模型的列表,以逗號分隔的列表。
假設我有一個Posts模型和相關的Tag, post.getTags()
獲取相關的模型,但是我看不到如何以可以產生正確輸出的方式將它們串聯起來。
在普通的PHP視圖中,我只是將HTML放入數組並implode(', ', $tagLinks)
。
如何用Volt實現相同的輸出?
在電壓引擎內創建一個過濾器。
$compiler = $volt->getCompiler();
$compiler->addFilter('joiner', function($resolvedArgs, $exprArgs) {
$text = 'implode(", ", ' . $resolvedArgs . ')';
return $text;
});
並在模板中使用該“聯接”過濾器。
{{ post.getTags() | joiner }}
最后。 如果您懶於創建過濾器或函數,則只需鍵入php代碼。 它在伏特上工作。
some tags : <?= implode(', ', $tagLinks) ?>
編輯:我認為伏特已經有join
過濾器。 參見http://docs.phalconphp.com/en/latest/reference/volt.html#filters
看到我想從模型中獲取格式化信息,我不能只使用普通的implode()或聯接過濾器。 根據Eugene的建議,我向Volt引擎添加了一個自定義函數,並為我的模型添加了一種方法,以獲取格式正確的信息。
自定義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);
}
將其添加到伏特:
$compiler = $volt->getCompiler();
$compiler->addFunction('joinModels', 'App\\Formatter::joinModels');
在模型中:
public function linkTo()
{
return Phalcon\Tag::linkTo('tags/' . urlencode($this->name), htmlspecialchars($this->name));
}
然后,最后,在我看來:
{% set postTags = post.getTags() %}
{% if postTags.count() %}
{{ joinModels(postTags, 'linkTo') }}
{% else %}
None
{% endif %}
非常感謝那些回答了我們的幫助。
已經有連接過濾器: {{ tagLinks|join(",") }}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.