CodeIgniter4 子視圖

2020-08-13 16:34 更新

子視圖允許你插入在控制器以外生成的 HTML 片段,但它只能調(diào)用指定類的方法,且該方法只能返回有效的 HTML 字符串內(nèi)容。這個可調(diào)用方法可以是在 項目中自動加載器可以定位到的任何可訪問類的任何方法,唯一的限制是該類的構(gòu)造方法不可有必須傳入的參數(shù)。使用這個功能后,對模塊化代碼有很好的幫助。

  1. <?= view_cell('\App\Libraries\Blog::recentPosts') ?>

在這個示例中,會自動運行 App\Libraries\Blog 類的 recentPosts() 方法,該方法必須返回有效的 HTML 字符串。該方法可以是 靜態(tài)方法,也可以是非靜態(tài)方法。

子視圖參數(shù)

可以通過 view_cell 方法的第二個參數(shù)向方法進行傳值來進一步優(yōu)化調(diào)用方式。參數(shù)支持鍵/值對的數(shù)組或鍵/值對的字符串(已逗號分隔):

  1. // 數(shù)組形式的參數(shù)
  2. <?= view_cell('\App\Libraries\Blog::recentPosts', ['category' => 'codeigniter', 'limit' => 5]) ?>
  3. // 字符串形式的參數(shù)
  4. <?= view_cell('\App\Libraries\Blog::recentPosts', 'category=codeigniter, limit=5') ?>
  5. public function recentPosts(array $params=[])
  6. {
  7. $posts = $this->blogModel->where('category', $params['category'])
  8. ->orderBy('published_on', 'desc')
  9. ->limit($params['limit'])
  10. ->get();
  11. return view('recentPosts', ['posts' => $posts]);
  12. }

此外,可以在方法中使用與參數(shù)變量匹配的參數(shù)名稱,以提高可讀性。當以這種方式使用它時,必須始終在視圖調(diào)用方法中指定所有參數(shù):

  1. <?= view_cell('\App\Libraries\Blog::recentPosts', 'category=codeigniter, limit=5') ?>
  2. public function recentPosts(int $limit, string $category)
  3. {
  4. $posts = $this->blogModel->where('category', $category)
  5. ->orderBy('published_on', 'desc')
  6. ->limit($limit)
  7. ->get();
  8. return view('recentPosts', ['posts' => $posts]);
  9. }

子視圖緩存

您可以通過傳遞緩存數(shù)據(jù)的秒數(shù)作為第三個參數(shù)來緩存子視圖的調(diào)用結(jié)果,默認將使用當前配置的緩存引擎。

  1. // 視圖將緩存 5 分鐘
  2. <?= view_cell('\App\Libraries\Blog::recentPosts', 'limit=5', 300) ?>

當然,你也可以自定義緩存視圖的文件名已替換默認的緩存文件名,通過第 4 個參數(shù)來自定義:

  1. // 視圖將緩存 5 分鐘,將緩存文件重新命名為 newcacheid
  2. <?= view_cell('\App\Libraries\Blog::recentPosts', 'limit=5', 300, 'newcacheid') ?>
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號