内容布局编译器用于在发布指定内容类型的内容项时输出内容布局的 HTML。
编译过程中,cec compile-content 命令将在与组件的 render.js 文件相同的位置查找 compile.js 文件:
src
components
<yourComponent>
assets
render.jscompile.js如果此文件不存在,将不编译布局并将在运行时呈现布局。
如果该文件确实存在,它需要实施 compile() 接口,其返回 Promise。例如,下面是一个内容布局编译器,后面是生成的 layout.html 输出:
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;
}
try {
// add in style - possibly 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
});
}
};
module.exports = ContentLayout;
生成的 layout.html 可以插入到 Web 应用程序中,也可以插入需要内容布局的静态 HTML 输出的任何其他地方。layout.html 与 compile.js 文件输出到相同目录。
{{{style}}}
{{#fields}}
<div class="author-container">
<span class="author-name" onclick='{{scsData.contentTriggerFunction}}("starter-blog-post_author eq \"{{author_id}}\"")'>{{starter-blog-author_name}}</span>
{{/fields}}