开发者

PHP templating challenge (optimizing front-end templates)

开发者 https://www.devze.com 2022-12-22 00:54 出处:网络
I\'m trying to do some templating optimizations and I\'m wondering if it is possible to do something like this:

I'm trying to do some templating optimizations and I'm wondering if it is possible to do something like this:

function table_with_lowercase($data) {
    $out = '<table>';
    for ($i=0; $i < 3; $i++) { 
        $out .= '<tr><td>';
        $out .= strtolower($data);
        $out .= '</td></tr>';
    }
    $out .= "</table>";

    return $out;
}   

NOTE: You do not know what $data is when you run this function.

Results in:

<table>
    <tr><td><?php echo strtolower($data) ?></td></tr>
    <tr><td><?php echo strtolower($data) ?></td></tr>
    <tr><td><?php echo strtolower($data) ?></td></tr>
</table>

General Case: Anything that can be evaluated (compiled) will be. Any time there is an unknown variable, the variable and the functions enclosing it, will be output in a string format.

Here's one more example:

function capitalize($str) {
    return ucwords(strtolower($str));
}

If $str is "HI ALL" then the output is:

  • Hi All

If $str is unknown then the output is:

In this case it would be easier to just call the function (ie. <?php echo capitalize($str) ?> ), but the example before would allow you to precompile your PHP to make it more efficient


Define a CSS style and make the client side do the work, instead of the server side.

change_case {
    text-transform: lowercase; /* force text to lowercase */
    text-transform: uppercase; /* force text to uppercase */
    text-transform: capitalize; /* force text to proper case */
}

<span="change_case">...</span>


It's definitely possible. But, writing an effective optimizing compiler for php is no easy task. A simplistic one would probably not offer significant benefit. The benefit is even questionable for a good one.


Your best bet is probably to use a separate templating language that generates optimised PHP code. Smarty is a popular choice.

0

精彩评论

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