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); // 开启缓存

$smarty->assign('name', '张三');
$smarty->assign('gender', '男');
$smarty->assign('birth', 2003);

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);

/**
 * 获取(当前)日期时间
 *
 * @file /smarty/libs/plugins/function.fdate.php
 * @param array $params 参数
 * @return string 日期时间字符串
 */
function smarty_function_fdate(array $params): string
{
    $format = (string)($params['format'] ?? '');

    $format === '' && $format = 'Y-m-d H:i:s';

    return date($format);
}



<!doctype html>
<html lang="zh">
<head>
    <meta charset="utf-8">
    <title>demo</title>
</head>
<body>
俺叫{MN:$name}({MN:$gender}),出生于{MN:$birth}年。<br>
--------------------------------------------------<br>
{MN:fdate format='Y'}<br>
{MN:fdate format='Y-m-d'}<br>
{MN:fdate format='Y-m-d H:i:s'}<br>
--------------------------------------------------<br>
{MN:fdate format="Y"}<br>
{MN:fdate format="Y-m-d"}<br>
{MN:fdate format="Y-m-d H:i:s"}<br>
</body>
</html>

Copyright © 2024 码农人生. All Rights Reserved