Enable the declaration of custom fields within specific template files, displaying corresponding editing interfaces during content editing. This would make custom templates more flexible. Currently, custom fields are either global or specific to individual posts, lacking template-specific options.
## 目的描述 目的是实现这样的功能:在具体的模板文件中,声明自定义字段,编辑时显示对应的编辑界面,使自定义模板更加灵活。 ## 需求分析 Typecho 的自定义字段是个很好的特性,目前主要有3种方式添加自定义字段: 1. 由主题的 `functions.php` 文件中的 `themeFields` 函数添加自定义字段。 2. 用插件接口 `getDefaultFieldItems` 添加自定义字段。 3. 后台编辑内容时,手动添加自定义字段。 方式1和方式2,都是对所有文章编辑有效,编辑任何文章/页面都会显示这些字段。 方式3,只对具体的单篇文章/页面有效。 缺少了更具有针对性的自定义字段,比如针对某个分类、某个模板文件所特有的自定义字段,不改动typecho源码的情况下,只能通过插件弥补。 我动手实现了针对具体模板文件的自定义字段支持的插件,在这里记录一下,晚些整理代码发到 github。 ## 应用实例 模板文件: ```php <?php /** * 模板 - A-0 * * @package custom * * @field {string} Color 自定义颜色 | 描述描述描述描述 */ ?> <?php echo $this->fields->Color; ?> ``` 该模板使用 `@field` 声明了1个自定义字段 `Color`,编辑时会显示对应的文本输入框,如下图所示。 后台效果: (仅当切换到该自定义模板时,才会显示这个字段)  使用 `@field` 声明也可以实现其它输入控件,如多行文本框,下拉列表,单选框,多选框。 模板文件: ```php <?php /** * 模板字段测试2 * * @package custom * @field {string} Color 自定义颜色1 | ["text",null,"green","描述描述描述描述111"] * @field {str} Height 自定义高度1 | 描述描述描述描述222 * @field {string} Color2 自定义