开发者

mysql/php - store html templates within the a database

I am wondering the best way to store html templates in a database where I am able to retrieve them and insert variables.

Obviously I could store them as php and then 'EVAL' the record.... but I heard it was evil.

is there a better way? :)

edit:

Sorry I wasn't clear... I tried to simplify it by saying htm开发者_开发问答l templates... what I really meant was small embed-able html elements (think youtube)... rather than an entire site.


I would also advice against storing the HTML inside the database. It's much more convenient to store them as templates on the file-system and include them or parse them when needed. I also recommend using something like Smarty. A very handy tool, that is.

However, if you would rather do it manually, here is what I would do.

First, I would store the template in a file on the file-system. If you would rather use a database, that can be done to. Just know that a database will, usually, cause more overhead when used for stuff like this.

For example, in the case of a YouTube video:

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

Then I would simply str_replace the PHP variables in there, much like PHP itself does with strings.

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

And that would be it.

You could of course use <?php $width; ?>-like placeholders and just include the template, but that leaves you at risk for injection attacks. This is the safer route.


Mark, do you need to store templates in the database? This will add a heavy burden to your DB server every time those templates are requested, unless you cache them.

Compare this to the filesystem which has built-in caches to streamline file reads.

Plus you won't have the potential security hole that may come from using eval().


No need to reinvent the wheel, you can use a templating engine and store the templates themselves in a database. Personally I like to store templates in the file-system because it makes things much simpler to maintain, but its your project :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜