将标签(例如{Blabla})送到PHP功能



我在大多数CMS和论坛模板中都看到了这一点。如何制作诸如{blabla}之类的HTML标签,以及如何将它们转发到PHP功能?

这些称为模板系统,这些"标签"的样式取决于您正在使用的模板系统。

PHP中的一个基本示例将是这样的:

page.tpl:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Basic templating system</title>
</head>
<body>
    <h2>Welcome to our website, {{name}} !</h2>
    <p>Please confirm your account. We've sent an email to: {{email}}</p>
</body>
</html>

index.php:

<?php
// Get the template's content
$template = file_get_contents("page.tpl");
// The data needed in the template
$data = array(
    'name' => 'John',
    'email' => 'john@smith.com',
);
// The template's tags pattern
$pattern = '{{%s}}';
// Preparing the $map array used to replace the template's tags with data values
$map = array();
foreach($data as $var => $value)
{
    $map[sprintf($pattern, $var)] = $value;
}
// Replace the tags with data values
$output = strtr($template, $map);
// Output the template with replaced tags
echo $output;
?>

我建议您查看已经存在的模板引擎,例如:小胡子,聪明或树枝,其他许多人

希望这会有所帮助:)

最新更新