从 PHP 函数返回 HTML 代码的最佳方法是什么?在速度和可用性问题上?
我正在使用变体 1,因为它最容易理解,但人们说我最慢,因为我在“”中有必须解析的代码。
我认为这不是使用 PHP 和 HTML 时使用的最佳实践是什么的重复问题?因为我谈论的是从 function返回代码,而不仅仅是从包含的文件中回显 HTML。
情况1
return "
<div class='title'>
<h5>
<a href='$permalink'>$title</a>
</h5>
</div>
<div id='content'>
$content
</div>
";
Run Code Online (Sandbox Code Playgroud)
案例二
$output = '
<div class="title">
<h5>
<a href="' . $permalink . '">' . $title . '</a>
</h5>
</div>
<div id="content">' .
$content .'
</div>
';
return $output;
Run Code Online (Sandbox Code Playgroud)
案例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;
Run Code Online (Sandbox Code Playgroud)
案例四
ob_start();
?>
<div class='title'>
<h5>
<a href="<?= $permalink ?>"><?= $title ?></a>
</h5>
</div>
<div id='content'>
<?= $content ?>
</div>";
<?php
return ob_get_clean();
Run Code Online (Sandbox Code Playgroud)
案例5
$output = <<<HTML
<div class='title'>
<h5>
<a href='$permalink'>$title</a>
</h5>
</div>
<div id='content'>
$content
</div>
HTML;
return $output;
Run Code Online (Sandbox Code Playgroud)
案例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>
Run Code Online (Sandbox Code Playgroud)
树枝文档
http://twig.sensiolabs.org/documentation
| 归档时间: |
|
| 查看次数: |
6475 次 |
| 最近记录: |