65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 PHP 和 JSON Schema 编辑 Bootstrap 菜单

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (2投票s)

2015 年 5 月 11 日

CPOL

1分钟阅读

viewsIcon

13621

使用 JSON Schema 在 PHP 中编辑 Bootstrap 菜单

引言

本文旨在分享一个关于 JSON Schema 的有趣资源和/或概念。

JSON 对于 JavaScript 来说非常有用,就像 XML 与 DTD 一样(https://w3schools.org.cn/xml/xml_dtd.asp),JSON 也有 Schema(https://json-schema.fullstack.org.cn/)。

这非常有趣,因为通过 Schema(数据类型),你可以指定值的类型,然后描述这种类型的值的格式,就像 SQL 表的 CRUD 操作一样。

在 jQuery 中有一个很棒的包可以帮助你实现这一点:https://github.com/jdorn/json-editor/

我想通过一个 PHP 中的 Bootstrap 菜单编辑器来演示这一点,你将会看到仅仅通过一个简单的 `datatype` 声明,表单可以变得多么复杂。

编辑菜单

一开始,你只有一个根条目。要添加菜单子项,请点击“属性”,然后选择“children”,并输入一个名称。

要预览你的工作,请点击“提交”。

Using the Code

JSON Schema 如下:

    schema: {
            title: "Menu",
            format: "grid",
            $ref: "#/definitions/menu",
            definitions: {
                menu: {
                    type: "object",
                    id: "menu",
                    headerTemplate: "{{ self.name }}",
                    // The object will start with only these properties
                    defaultProperties: [
                        "name",
                        "children"
                    ],
                    properties: {
                        name: {
                            title: "Name",
                            type: "string"
                        },
                        isdivider: {
                            title: "divider",
                            type: "string",
                            "enum": [false,true]
                        },
                        children: {
                          type: "array",
                          // Self-referential schema in array items
                          items: {
                            title: "Children",
                            $ref: "#/definitions/menu"
                          }
                        }
                    }
                }
            }

jQuery 插件通过以下行调用:

var editor = new JSONEditor(document.getElementById('editor_holder'),{

有一个重要的变量(menu),它包含 PHP 对象类型的 JSON 值。

Schema 描述了一个递归结构,其中包含可能的字段(nameisdividerchildren)。

渲染菜单的部分是 recursive_menu 函数。

function recursive_menu( $obj ,$deep)

关注点

关于这个 JSON Schema 有一个有趣的观点,如果你想改变技术,那么在不改变所有内容的情况下也是可能的,这就是它的可重用性。

例如,如果你想转向 Angularjs,这很容易实现,因为 Angular js 也有类似的东西 https://github.com/Textalk/angular-schema-form

然后,你可以用 Angularjs 重用你的 JSON Schema,Python 也是一样。

© . All rights reserved.