【问题标题】:Forwarding tags like {blabla} to php functions将 {blabla} 等标签转发到 php 函数
【发布时间】:2014-03-08 09:53:31
【问题描述】:

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

【问题讨论】:

  • forward them to php functions? 什么意思?能具体一点吗?
  • preg 替换,str 替换,我猜......但是,这会减慢应用程序的速度,实际上并不需要它,恕我直言。 :) 有人说 - php 是它自己的模板语言。 :) stackoverflow.com/a/5888214/2045185
  • 尝试使用一些模板脚本 smarty 使用类似的标签。还有另一个关于比较的链接webresourcesdepot.com/19-promising-php-template-engines
  • 您的问题似乎过于宽泛/未尝试/不清楚。不应利用赏金将此社区用作免费的代码编写服务。我觉得这个问题应该在赏金结束后改进或关闭。

标签: php html web tags


【解决方案1】:

这些被称为模板系统,这些“标签”的样式取决于您使用的模板系统。

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;

?>

我建议您检查现有的模板引擎,例如:MustacheSmartyTwig 以及许多其他引擎

希望这会有所帮助:)!

【讨论】:

  • Twig 是一个非常好的模板引擎(基于 python 的 Jinja2)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-27
  • 1970-01-01
  • 2020-01-09
  • 1970-01-01
  • 2012-04-19
相关资源
最近更新 更多