rjvandoesburg/laravel-nova-templating

根据模型和资源加载模板

1.0.2 2019-11-14 14:25 UTC

This package is auto-updated.

Last update: 2024-09-15 01:48:19 UTC


README

让您的 Nova 资源决定需要加载哪个前端模板。

本包受到WordPress 模板层次结构的启发。

此包将为您的应用程序添加一个端点,并使用 Nova 解决资源和相关模型。该端点将返回一个名称数组,例如您可以在前端应用程序中使用的模板层次结构,以“动态”渲染页面。

要求

此包需要 Laravel 5.8 或更高版本,PHP 7.2 或更高版本。

安装

您可以通过 composer 安装此包

composer require rjvandoesburg/laravel-nova-templating

要添加端点,请将以下内容添加到路由文件中,您可以根据需要应用自己的组和中间件!

Route::novaResourceTemplateRoute();

这将向您的应用程序添加 /template-api/{resource}/{resourceId}

此包将自动注册自己。

用法

一旦将路由添加到您的应用程序,您就可以从 API 中检索模板名称列表。

curl --GET {url}/api/template-api/users/1

因为这是基于 Laravel Nova 的,所以 resource 需要与资源或 public static function uriKey() 中定义的名称相同。resourceId 是模型的 ID。

它可以返回如下结果:

{
  "templates": [
    "user-1",
    "user",
    "resource",
    "model",
    "index"
  ],
  "resource": "users",
  "resourceId": "1"
}

目前,此包按照以下方式构建模板列表:

  • {resource}-{modelKey}
  • {resource}
  • {model}-{modelKey}
  • {model}
  • resource
  • model
  • index

注意,当资源名称与模型名称不同时,才会出现 resource。

VueJs

假设您想在 Vue 中使用此功能,以下是如何实现此功能的示例

const files = require.context('./templates/', true, /\.vue$/i);
files.keys().map(key => Vue.component('template-'+key.split('/').pop().split('.')[0], files(key).default));

app.js,我在 templates 文件夹中加载所有文件,并在注册时将 template 作为名称的前缀。

  • templates/index.vue 将被注册为 template-index
  • templates/user.vue 将被注册为 template-user
  • templates/user-1.vue 将被注册为 template-user-1

创建一个 Vue 文件,它将在特定的路由上渲染。在示例中,我使用 vue-routerbeforeRouteEnter 根据当前 URL 获取正确的模板。

<template>
    <component :is="`template-${template}`"></component>
</template>

<script>
    export default {
        beforeRouteEnter(to, from, next) {
            return axios.get(`/template-api${path}`)
                .then(({data: response}) => {
                    this.route = response
                })
                .then(next)
                .catch(error => {
                    // Show an error or redirect to an error page, dealer's choice
                })
        },

        data: () => ({
            template: null,
            route: null,
        }),

        created() {
            _.forEach(this.route.templates, template => {
                if (Vue.options.components[`template-${template}`] !== undefined) {
                    this.template = template
                    return false
                }
            })
        },
    }
</script>

禁用资源模板

因此,所有内容都已启动,使用通配符进行路由,但您不希望人们访问某些模型。您可以通过实现以下接口来禁用(默认启用)特定资源的模板:Rjvandoesburg\NovaTemplating\Contracts\Templatable。这将添加 isTemplatable(Request $request) 方法,您可以在其中添加自己的逻辑来决定给定的资源是否可以模板化。

处理失败

当找不到资源或抛出异常时,将返回一个包含错误状态代码的 JSON 响应(默认回退到索引),其中包含错误模板名称。

{
  "templates": [
    "404",
    "500",
    "index"
  ]
}

在 Promise 中,您仍然可以通过 catch 访问响应,因此如何处理错误取决于您。

待办事项

  • 允许用户扩展模板构建器以更改 API 的输出(例如,他们想使用别名或使用分类的名称作为模板)
  • 更好的/更多的/动态错误模板
  • 向未找到路由添加错误消息

贡献

请参阅贡献指南获取详细信息。

致谢

特别感谢Spatie,他们的指导方针和他们的包为我们提供了灵感。

许可证

MIT许可证(MIT)。有关更多信息,请参阅许可证文件