Smarty模板引擎创建块标签

<?php
declare(strict_types=1);
ini_set('display_errors', 'On');
error_reporting(-1);

require_once __DIR__ . '/smarty/libs/Smarty.class.php';

$smarty = new Smarty();

$smarty->setTemplateDir(__DIR__ . '/smarty_template');
$smarty->setCompileDir(__DIR__ . '/smarty_compile');
$smarty->setCacheDir(__DIR__ . '/smarty_cache');
$smarty->setConfigDir(__DIR__ . '/smarty_config');

$smarty->setLeftDelimiter('{MN:');
$smarty->setRightDelimiter('}');

$smarty->setCaching(Smarty::CACHING_OFF); // 关闭缓存
// $smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT); // 开启缓存

try {
    $smarty->display('demo.htm');
} catch (SmartyException $e) {
    exit('SmartyException: ' . $e->getMessage());
} catch (Exception $e) {
    exit('Exception: ' . $e->getMessage());
}
 
 
 
<?php
declare(strict_types=1);
ini_set('display_errors', 'On');
error_reporting(-1);

/**
 * {MN:blist}标签
 *
 * @file /smarty/libs/plugins/block.blist.php
 * @param array $params 参数
 * @param string|null $content 块标签里的内容
 * @return string 块标签最终HTML代码
 */
function smarty_block_blist(array $params, string|null $content): string
{
    $html = '';

    // 显示多少条记录,若缺省row参数或row参数不合法则显示10条
    $row = (int)($params['row'] ?? 10);
    $row < 0 && $row = 10;

    $content === null && $content = '';
    if ($content !== '') {
        $data = [
            ['name' => '刘一', 'gender' => '男', 'birth' => 2001],
            ['name' => '陈二', 'gender' => '女', 'birth' => 2002],
            ['name' => '张三', 'gender' => '男', 'birth' => 2003],
            ['name' => '李四', 'gender' => '女', 'birth' => 2004],
            ['name' => '王五', 'gender' => '男', 'birth' => 2005],
            ['name' => '赵六', 'gender' => '女', 'birth' => 2006],
            ['name' => '孙七', 'gender' => '男', 'birth' => 2007],
            ['name' => '周八', 'gender' => '女', 'birth' => 2008],
            ['name' => '吴九', 'gender' => '男', 'birth' => 2009],
            ['name' => '郑十', 'gender' => '女', 'birth' => 2010],
        ];

        for ($i = 0; $i < $row; $i++) {
            if (!isset($data[$i])) {
                break;
            }

            // 替换占位内容
            $str = str_replace(
                [
                    '[field:name]',
                    '[field:gender]',
                    '[field:birth]'
                ],
                [
                    $data[$i]['name'],
                    $data[$i]['gender'],
                    $data[$i]['birth']
                ],
                $content
            );
            $html .= $str;
        }
    }

    return $html;
}
 
 
 
<!doctype html>
<html lang="zh">
<head>
    <meta charset="utf-8">
    <title>demo</title>
</head>
<body>
{MN:blist row="5"}
俺叫[field:name]([field:gender]),出生于[field:birth]年。
{MN:/blist}
</body>
</html>

Copyright © 2024 码农人生. All Rights Reserved