💎 函 数 式 模 板 引 擎

v0.1.2 版本
2025-02-14 版本更新时间
3 安装
1 star

简介

虽然PHP 是一种很强大的 Web 开发语言,但是HTML 和 PHP 代码参杂一起,不易于书写和阅读;
使用 PHP 函数式实现 HTML 页面的方式,可以代替传统的 view 页面,而无需手写 HTML5 代码;

安装

composer require kingbes/fun-view

使用

示例一 普通使用

main.php

require "./vendor/autoload.php";

use Kingbes\FunView\Template;

// 内容
$tpl = new Template([
    // 模板目录
    "view_dir" =>  __DIR__ . DIRECTORY_SEPARATOR . "view" . DIRECTORY_SEPARATOR
]);

echo $tpl->fetch("index", ["num" => 3]);

模板页 index.php

use function Kingbes\FunView\{
    p,
    hsc,
    html,
    h1,
    span,
    img,
    head,
    body,
    title,
    meta,
    div,
    style,
    script
};

$view = html(
    head(
        meta(["charset" => "UTF-8"]),
        meta([
            "name" => "viewport",
            "content" => "width=device-width, initial-scale=1.0"
        ]),
        title("这个是个标题"),
        style([
            "p" => [
                "color" => "blue",
            ]
        ])
    ),
    body(
        p("hello world"),
        h1("下面是循环<br/>:"),
        div(function () use ($num) {
            $div = "";
            for ($i = 0; $i < $num; $i++) {
                $div .= div("循环:$i");
            }
            return $div;
        }),
        h1(
            "world",
            ["style" => "color:red;", "id" => "1"],
            span(" hello")
        ),
        img(["src" => "https://unpkg.com/outeres/demo/carousel/720x360-1.jpg"]),
        div(hsc("<h1>安全输出</h1>")),
        script("alert('hello world')")
    )
);
// 显示模板
echo $view;

示例二 webman使用

配置文件 config/view.php

<?php
/**
 * This file is part of webman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author    walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link      http://www.workerman.net/
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */

use support\view\Raw;
use support\view\Twig;
use support\view\Blade;
use support\view\ThinkPHP;
// 新增use
use Kingbes\FunView\FunView;

return [
    // 配置FunView类
    'handler' => FunView::class
];

控制器IndexController.php

<?php

namespace app\controller;

use support\Request;

class IndexController
{

    public function view(Request $request)
    {
        // 常规使用即可
        return view('index/view', ['name' => 'webman']);
    }
}

视图文件view/index/view.php

<?php

use function Kingbes\FunView\{
    hsc,
    html,
    head,
    body,
    title,
    meta,
    div
};

$view = html(
    head(
        meta(["charset" => "UTF-8"]),
        meta([
            "name" => "viewport",
            "content" => "width=device-width, initial-scale=1.0"
        ]),
        title("这个是个标题")
    ),
    body(
        div("wellcome to ", hsc($name)),
    )
);
// 显示
echo $view

效果图

更多信息查看 GITHUB

赞助商