說明如何在 CodeIgniter 內透過 library 建立可以共同使用的 JSON-LD 資料,這樣如果有些頁面想要重複使用比如說是像 website、organization 資料時就不用找出所有有用到的地方都改一次了。
首先,建立一個名為 JsonLdLibrary.php 的函式庫檔案,並將其放在 application/libraries 目錄下。
class JsonLdLibrary {
public function __construct()
{
// Assign the CodeIgniter super-object
$this->ci =& get_instance();
}
public function person(){
$jsonLd=array(
"@context" => "https://schema.org",
"@type" => "Person",
"name" => "deathhell",
"url"=> $this->ci->data["siteUrl"],
...
);
return $jsonLd;
}
public function website(){
$jsonLd=array(
...
);
return $jsonLd;
}
}
在 Controller 中使用函式庫生成 JSON-LD 資料。
$this->load->library('JsonLdLibrary');
$jsonLd=[
$this->jsonldlibrary->website(),
$this->jsonldlibrary->person(),
...
];
$data = compact('jsonLd'...);
在 View 中嵌入 JSON-LD 資料。
<script type="application/ld+json">
<?= json_encode($jsonLd, JSON_PRETTY_PRINT) ?>
</script>
這樣就可以在不同頁面間共用相同的 JSON-LD 資料了。