我想知道将 html 模板存储在数据库中的最佳方式,以便我能够检索它们并插入变量。
显然我可以将它们存储为 php,然后“评估”记录....但我听说这很糟糕。
有没有更好的办法? :)
编辑:
抱歉,我不清楚……我试图通过说 html 模板来简化它……我真正的意思是小型可嵌入的 html 元素(想想 youtube)……而不是整个网站。
最佳答案
我还建议不要将 HTML 存储在数据库中。将它们作为模板存储在文件系统上并在需要时包含或解析它们要方便得多。我还建议使用像 Smarty 这样的东西。这是一个非常方便的工具。
但是,如果您更愿意手动操作,我会这样做。
首先,我会将模板存储在文件系统上的一个文件中。如果您宁愿使用数据库,也可以这样做。只要知道数据库在用于此类事情时通常会导致更多开销。
例如,对于 YouTube 视频:
<object width="{$width}" height="{$height}">
<param name="movie" value="http://www.youtube.com/{$path}"></param>
<param name="allowFullScreen" value="true"></param>
<param name="allowscriptaccess" value="always"></param>
<embed src="http://www.youtube.com/{$path}"
type="application/x-shockwave-flash"
allowscriptaccess="always"
allowfullscreen="true"
width="{$width}" height="{$width}">
</embed>
</object>
然后我会简单地 str_replace
那里的 PHP 变量,就像 PHP 本身对字符串所做的一样。
<?php
$template_path = 'templates/youtube_vid.tpl';
$template_data = file_get_contents($template_path);
$old = array('{$width}', '{$height}', '{$path}');
$new = array(425, 344, 'v/zuZB2O6orV0&hl=en_US&fs=1&');
echo str_replace($old, $new, $template_data);
?>
就是这样。
你当然可以使用 <?php $width; ?>
-like 占位符和 include
模板,但这会让您面临注入(inject)攻击的风险。这是更安全的路线。
关于php - mysql/php - 在数据库中存储 html 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1827933/