用 Framer 组件自动生成关键词标签
Apr 27 ·
2 分钟阅读
在 Pixyer 的 Gallery 详情中左侧底部显示了 Photo Highlight,记录了这张图片的一些关键词,我们的原始数据为这样的格式:
table next to a vase of flowers, cozy, full product shot, pink zen style, designed for cozy aesthetics, product introduction photo, high detail product photo
如果要靠人工把这些关键词逐一拆分、录入,这将是一件费时费力的工作,而且每张图片的词数不一样,这在 Framer CMS 上需要多个字段来管理储存,也很不方便和灵活。
基于这样的情况,我决定直接使用代码创建一个小组件,自动完成以下几件事情:
- 根据
,
把原数据拆分为单个的词组 - 将每个词组首字母大写
- 为每个词添加统一的 Tag 样式
- 使用 Flex 布局自动排版所有 Tag
代码如下:
import { addPropertyControls, ControlType } from "framer"
/** * These annotations control how your component sizes * Learn more: https://www.framer.com/developers/#code-components-auto-sizing * * @framerSupportedLayoutWidth auto * @framerSupportedLayoutHeight auto */export default function Text(props) { const { text } = props
// Split by commas, capitalize first letter of each phrase const formattedText = text.split(",").map((phrase) => { const trimmedPhrase = phrase.trim() return trimmedPhrase.charAt(0).toUpperCase() + trimmedPhrase.slice(1) })
return ( <div style={containerStyle}> {formattedText.map((phrase, index) => ( <span key={index} style={tagStyle}> {phrase} </span> ))} </div> )}
// Define property controls for the componentaddPropertyControls(Text, { text: { title: "Text", type: ControlType.String, defaultValue: "Photo Highlights", },})
// Updated stylesconst containerStyle = { display: "flex", flexWrap: "wrap", gap: "12px",}
const tagStyle = { backgroundColor: "white", padding: "8px 16px", borderRadius: "999px", color: "#333333", fontSize: "14px",}
现在,只需要在页面中使用这个组件,并填入原始数据就行了,在这里我直接绑定了在 CMS 中的 Prompt 数据。

如果你需要其他调整,比如使用不同的分割符来分割文本、按照首字母分组(适用于显示联系人和国家城市等场景)或者改下 Grid 布局等,在上面代码的基础上,只需要一点小调整就能实现。
编辑于 Apr 27