扩展 Laravel 个模板函数

Extend Laravel template functions

最好的转换方法是什么:

<div id="{{ $stat->type }}-{{ 
    str_replace(' ', '-', strtolower($stat->description))
    }}-chart">
</div>

进入这个:

<div id="{{getDivId($stat)}}">

我的意思是,我需要创建在 blade 模板中使用的函数,我在 laravel 文档中找到了使用 @ 的东西,但我不想这样做使用 @,我想使用 {{ }}

如果我没有很多的话,我喜欢把它放在我的模型上。 $appends 数组将其添加到每个查询中。

Stat.php

protected $appends = array('div_id');

public function getDivIdAttribute()
{
  return $this->type .'-'
    .str_replace(' ', '-', strtolower($this->description));
}

然后您可以在 blade 模板上像这样访问它。

<div id="{{ $stat->divId }}">

如果您有很多,您可能想考虑使用 Presenter class。