大多数开发者生成图像的方式如下:
const html = `
<div style="...">
<h1>${post.title}</h1>
<p>${post.author} · ${post.date}</p>
</div>
`;
这种方法起初可行,但并非始终有效。
- 特殊字符会破坏 HTML 结构(标题中的
&、<、>) - 模板不断膨胀,字符串变得难以维护
- 在不同环境中复用同一模板会变得混乱不堪
- 设计与数据之间缺乏清晰的分离
更简洁的方法:模板变量
不要将值直接插入到 HTML 字符串中,而是将它们单独传递:
const response = await fetch('https://renderpix.dev/v1/render', {
method: 'POST',
headers: {
'X-API-Key': 'rpx_your_key',
'Content-Type': 'application/json'
},
body: JSON.stringify({
html: `
<div style="width:1200px;height:630px;background:#0f172a;
display:flex;flex-direction:column;justify-content:center;
padding:80px;font-family:sans-serif">
<div style="color:#22d3ee;font-size:18px">{{domain}}</div>
<div style="color:white;font-size:52px;font-weight:bold;line-height:1.2">
{{title}}
</div>
<div style="color:#94a3b8;font-size:20px;margin-top:24px">
{{author}} · {{date}}
</div>
</div>
`,
vars: {
title: post.title,
author: post.author,
date: post.publishedAt免责声明:本文内容来自互联网,该文观点不代表本站观点。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请到页面底部单击反馈,一经查实,本站将立刻删除。