如何在Laravel Statamic中创建可复用HTML块用于Vue.js多页面?
实现方案说明
完全可以实现你的需求,Statamic的蓝图(Blueprints)和字段集(Fieldsets)结合Replicator字段就是解决这类可复用、可排序内容块的最佳方案,具体步骤如下:
1. 创建可复用字段集(Fieldset)
先定义横幅块的字段结构,所有页面的横幅块都共用这个结构。在resources/fieldsets目录下新建banner_block.yaml,示例配置:
title: 横幅图片块 fields: - handle: banner_image field: type: assets container: assets folder: banners restrict: true allow_uploads: true title: 横幅图片 - handle: banner_title field: type: text title: 横幅标题 - handle: banner_button_text field: type: text title: 按钮文本 default: 了解更多 - handle: banner_button_link field: type: link title: 按钮链接
2. 在页面蓝图中集成Replicator字段
编辑页面的蓝图(比如resources/blueprints/pages/default.yaml),添加Replicator字段,将刚才的banner_block作为可选择的区块类型,同时还可以添加其他类型的块(比如文本块、卡片块):
sections: main: display: 页面内容 fields: - handle: page_blocks field: type: replicator title: 页面内容块 sets: banner: display: 横幅块 fieldset: banner_block # 可以添加其他块类型,比如文本块 text_block: display: 文本块 fieldset: text_block
这样管理员在编辑首页、关于页等页面时,就能自由添加、删除、拖拽排序横幅块(或其他块),并且每个块都能独立修改内容。
3. 通过Statamic API获取数据并在Vue中渲染
使用Statamic的REST API(默认启用,路径如/api/pages/home)获取页面数据,返回的page_blocks字段会包含所有添加的区块数据。在Vue组件中遍历这些数据,根据区块类型渲染对应的HTML:
<template> <div class="page-content"> <div v-for="(block, index) in pageBlocks" :key="index"> <!-- 渲染横幅块 --> <div v-if="block.type === 'banner'" class="banner-block"> <img :src="block.banner_image[0].url" :alt="block.banner_title"> <h2>{{ block.banner_title }}</h2> <a :href="block.banner_button_link.url" class="banner-button"> {{ block.banner_button_text }} </a> </div> <!-- 可以添加其他块的渲染逻辑 --> </div> </div> </template> <script setup> import { ref, onMounted } from 'vue'; import axios from 'axios'; const pageBlocks = ref([]); onMounted(async () => { // 根据当前页面slug获取数据,这里以首页为例 const response = await axios.get('/api/pages/home'); pageBlocks.value = response.data.data.page_blocks; }); </script>
关键特性支持说明
- 动态修改内容:每个页面的横幅块内容都是独立存储的,管理员在后台编辑对应页面时直接修改即可,无需影响其他页面。
- 移动块排序:Statamic后台的Replicator字段自带拖拽排序功能,管理员直接拖动区块就能调整展示顺序。
- 跨页面复用块结构:通过Fieldsets定义的块结构可以在任意页面蓝图中复用,保证所有横幅块的字段一致性。
内容的提问来源于stack exchange,提问作者Harris
相关产品推荐
相关产品推荐

