从PHP函数返回HTML的最佳实践

时间:2016-06-06 12:10:55

标签: php

从PHP函数返回HTML代码的最佳方法是什么?在速度和可用性方面?

我正在使用变体1,因为它是最容易理解的,但是人们说我最慢,因为我的内部代码是" "必须解析。

我认为这不是来自What is the best practice to use when using PHP and HTML?的重复问题,因为我在谈论从函数返回代码,而不仅仅是从包含文件中回显HTML。

案例1

return "    
<div class='title'>
    <h5>        
        <a href='$permalink'>$title</a>
    </h5>
</div>
<div id='content'>
    $content
</div>
";

案例2

$output = '
<div class="title">
    <h5>        
        <a href="' . $permalink . '">' . $title . '</a>
    </h5>
</div>
<div id="content">' .
    $content .'
</div>
';
return $output;

案例3

$output  = '<div class="title">';
$output .= '<h5>';
$output .= '<a href="' . $permalink . '">' . $title . '</a>';
$output .= '</h5>';
$output .= '</div>';
$output .= '<div id="content">';
$output .= $content; 
$output .= '</div>';
return $output;

案例4

ob_start();
?>
<div class='title'>
    <h5>
        <a href="<?= $permalink ?>"><?= $title ?></a>
    </h5>
</div>
<div id='content'>
    <?= $content ?>
</div>";
<?php
return ob_get_clean();

案例5

$output = <<<HTML
<div class='title'>
    <h5>        
        <a href='$permalink'>$title</a>
    </h5>
</div>
<div id='content'>
    $content
</div>
HTML;
return $output;

1 个答案:

答案 0 :(得分:0)

案例6:

让PHP处理数据并让你的模板工具处理HTML(你可以使用PHP作为模板工具,但像Twig这样的东西要好得多)

<?php
function doSomething(){
    return [
        'permalink' => 'https://some.where',
        'title' => "Title",
        'Content' => "Hello World!",
    ];

}

$template = $twig->loadTemplate('template.twig.html');
$template->render(doSomething());

//content of template.twig.html
<div class='title'>
    <h5>        
        <a href='{{permalink}}'>{{title}}</a>
    </h5>
</div>
<div id='content'>
    {{content}} 
</div>

Twig文档

http://twig.sensiolabs.org/documentation