คอมไพเลอร์ขององค์ประกอบ

คอมไพเลอร์ขององค์ประกอบที่กำหนดเองทั้งหมดจะมีโมเดลเดียวกับคอมไพเลอร์ของเพจ และสามารถสร้างขึ้นสำหรับเลย์เอาต์ส่วน องค์ประกอบที่กำหนดเอง และเลย์เอาต์ของเนื้อหา

ระหว่างการคอมไพล์ คำสั่ง cec compile-template จะค้นหาไฟล์ compile.js ในตำแหน่งเดียวกับไฟล์ render.js สำหรับองค์ประกอบ

  • src
    • components
      • <yourComponent>
        • assets
          • render.js
          • compile.js

หากไม่มีไฟล์นี้ ระบบจะไม่คอมไพล์องค์ประกอบและจะแสดงองค์ประกอบขณะรันไทม์

ในกรณีที่ไม่มีไฟล์ จะต้องใช้อินเตอร์เฟซ compile() ซึ่งแสดง Promise ตัวอย่างเช่น 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;