自訂「元件編譯器」全都遵循與頁面編譯器相同的模型,可針對區段版面配置、自訂元件和內容版面配置加以建立。
在編譯期間,cec compile-template
命令會尋找和元件的 render.js
檔案相同位置中的 compile.js
檔案:
src
components
<yourComponent>
assets
render.js
compile.js
如果此檔案不存在,便不會編譯該元件,並且在程式實際執行時呈現該元件。
如果此檔案存在,則必須實行會傳回承諾的 compile()
介面。例如,下列 Starter-Blog-Author-Summary
是自訂內容版面配置編譯器:
var fs = require('fs'), path = require('path'), mustache = require('mustache'); var ContentLayout = function (params) { this.contentClient = params.contentClient; this.contentItemData = params.contentItemData || {}; this.scsData = params.scsData; }; ContentLayout.prototype = { contentVersion: '>=1.0.0 <2.0.0', compile: function () { var compiledContent = '', content = JSON.parse(JSON.stringify(this.contentItemData)), contentClient = this.contentClient; // Store the id content.fields.author_id = content.id; if (this.scsData) { content.scsData = this.scsData; contentType = content.scsData.showPublishedContent === true ? 'published' : 'draft'; secureContent = content.scsData.secureContent; } // calculate the hydrate data content.hydrateData = JSON.stringify({ contentId: content.id, authorName: content.fields['starter-blog-author_name'] }); try { // add in style - possible to add to <head> but inline for simplicity var templateStyle = fs.readFileSync(path.join(__dirname, 'design.css'), 'utf8'); content.style = '<style>' + templateStyle + '</style>'; var templateHtml = fs.readFileSync(path.join(__dirname, 'layout.html'), 'utf8'); compiledContent = mustache.render(templateHtml, content); } catch (e) { console.error(e.stack); } return Promise.resolve({ content: compiledContent, hydrate: true // note that we want to hydrate this component using the render.js hydrate() function. This is required for when the user clicks on the author }); } }; module.exports = ContentLayout;