你需要的两种方法
GrapesJS 将当前页面以字符串 editor.getHtml() 形式暴露:对于
标记和 editor.getCss() 样式。其他所有东西——满了
文档、下载、ZIP——这些都是建立在这两者的基础上。
1. 阅读HTML和CSS
const html = editor.getHtml();
const css = editor.getCss();
2. 整理完整文档
const doc = `<!doctype html>
<html>
<head><meta charset="utf-8"><style>${css}</style></head>
<body>${html}</body>
</html>`;
// Store `doc`, or render it server-side.
3. 显示出口模态
// Built-in: opens a modal with the current HTML/CSS for copy-paste.
editor.runCommand('export-template');
4. 下载ZIP(index.html + style.css)
import grapesjs from 'grapesjs';
import exportPlugin from 'grapesjs-plugin-export';
const editor = grapesjs.init({
container: '#gjs',
plugins: [exportPlugin],
pluginsOpts: { 'grapesjs-plugin-export': {} },
});
// Trigger the ZIP download:
editor.runCommand('gjs-export-zip');
提示:控制包含哪些CSS
// e.g. include rules even for components not currently on the canvas
const css = editor.getCss({ keepUnusedStyles: true });
小贴士
将导出地址与目的地匹配。对于电子邮件,可以内联使用 CSS(通过类似 juice的工具,或者用 MJML 预设构建),因为大多数客户端会忽略 <style> 块。对于可复用模板,请传递 getCss({ keepUnusedStyles: true }) ,确保当前不在画布上的组件规则得以保留。ZIP 导出 grapesjs-plugin-export 工具很适合交接,但对于程序化出版,则需要直接读取 getHtml()/getCss() 存储。无论目标是什么,如果编辑者对不信任的用户开放,发布前应对标记进行净化。
前提条件
你需要一个正在运行的GrapesJS编辑器。以下内容基于两种方法——
editor.getHtml() 以及 editor.getCss() —— 返回字符串
你可以存储、渲染或打包。
控制包含哪些CSS
getCss() 接受各种选项。保留当前未在
canvas(对可复用模板非常有用),或通过特定组件范围:
const css = editor.getCss({ keepUnusedStyles: true });
导出邮件(内联CSS)
大多数邮件客户端会忽略 <style> 块,所以在CSS之前内联 CSS
发送——要么用MJML预设构建,要么通过
内联插件如下 juice:
import juice from 'juice';
const inlined = juice(`<style>${editor.getCss()}</style>${editor.getHtml()}`);
下载压缩包
import exportPlugin from 'grapesjs-plugin-export';
const editor = grapesjs.init({ container: '#gjs', plugins: [exportPlugin] });
editor.runCommand('gjs-export-zip'); // index.html + style.css
程序化地持续执行导出
关于发布,直接阅读字符串并发布到后台,而不是
依赖下载——存储 html、 css, 和 完整
project 所以页面既渲染得很快,又能在编辑器中重新打开。
最佳实践
导出地址与目的地匹配:邮件内联CSS,完整文档 独立页面,CMS的独立html/css列。Sanitise 出口加价之前 如果编辑对不受信任的用户开放,就发布。把你存储的项目版本改成这样 你可以回滚错误的编辑。
下一步
用 存储管理器后端 引导,或者将导出为可重复使用的包装 自定义插件。浏览 GrapesJS 插件 GJS。市场。
常见问题
我该如何从 GrapesJS 中提取 HTML 和 CSS?
editor.getHtml() 并返 editor.getCss() 还加价
以及风格作为弦乐。
我该如何让用户下载ZIP?
添加 grapesjs-plugin-export 并运行
gjs-export-zip 命令下载index.html加style.css。
getCSS 只包含已使用样式吗?
默认情况下,它返回当前页面的管理样式;通行选项如
keepUnusedStyles 改变这种状况。
