通过 PHP 插入 HTML 的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/261338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:06:41  来源:igfitidea点击:

What is the best way to insert HTML via PHP?

phphtmltemplate-engine

提问by Brayn

Talking from a 'best practice' point of view, what do you think is the best way to insert HTML using PHP. For the moment I use one of the following methods (mostly the latter), but I'm curious to know which you think is best.

从“最佳实践”的角度来看,您认为使用 PHP 插入 HTML 的最佳方式是什么。目前我使用以下方法之一(主要是后者),但我很想知道您认为哪种方法最好。

<?php
  if($a){
?>
[SOME MARKUP]
<?php
  }
  else{
?>
[SOME OTHER MARKUP]
<?php
  }
?>

Opposed to:

反对:

<?php
  unset($out);
  if($a) $out = '[SOME MARKUP]';
  else $out = '[OTHER MARKUP]';
  print $out;
?>

采纳答案by Kent Fredric

If you are going to do things that way, you want to separate your logic and design, true.

如果你打算那样做,你想把你的逻辑和设计分开,真的。

But you don't need to use Smarty to do this.

但是您不需要使用 Smarty 来执行此操作。

Priority is about mindset. I have seen people do shocking things in Smarty, and it eventually turns into people developing sites inSmarty, and then some bright spark will decide they need to write a template engine in Smarty (Never underestimate the potential of a dumb idea).

优先考虑的是心态。我看到人们在 Smarty 中做了令人震惊的事情,最终变成人们Smarty 中开发网站,然后一些明亮的火花会决定他们需要在 Smarty 中编写模板引擎(永远不要低估愚蠢想法的潜力)。

If you break your code into two parts and force yourself to adhere to a standard, then you'll get much better performance.

如果您将代码分成两部分并强迫自己遵守某个标准,那么您将获得更好的性能。

PageLogic.php

页面逻辑.php

<?php 

  $pageData = (object)(array());  // Handy trick I learnt. 

  /* Logic Goes here */


 $pageData->foo = SomeValue; 

 ob_start(); 
 require("layout.php"); 
 ob_end_flush();

Layout.php

布局.php

 <html>
   <!-- etc -->
   <?php for ( $i = 1; $i < 10; $i++ ){ ?>
    <?php echo $pageData->foo[$i]; ?>
   <?php } ?>
   <!-- etc -->
</html>

PHP Was written as a templating engine, so you at least should tryto use it for its designed task before assessing whether or not you need to delve into Smarty.

PHP 是作为模板引擎编写的,因此在评估是否需要深入研究 Smarty 之前,您至少应该尝试将其用于其设计任务。



Moreover, if you decide to use a templating engine, try get one that escapes HTML by defaultand you "opt out" instead of "opt in." You'll save yourself a lot of XSS headaches. Smarty is weak in this respect, and because of this, there are a lot of content-na?ve templates written in it.

此外,如果您决定使用模板引擎,请尝试使用默认转义 HTML 的模板引擎,然后“选择退出”而不是“选择加入”。你会为自己省去很多 XSS 的麻烦。Smarty 在这方面比较弱,正因为如此,里面写了很多内容原生的模板。

{if $cond}
    {$dangerous_value}
{else}
    {$equally_dangerous_value}
{/if}

Is generally how Smarty templates go. The problem is $dangerous_value can be arbitrary HTML and this just leads to even morebad coding practices with untraceable spaghetti code everywhere.

通常是 Smarty 模板的方式。问题是 $dangerous_value 可以是任意的 HTML,这只会导致糟糕的编码实践,到处都是无法追踪的意大利面条式代码。

Any template language you consider shouldcater to this concern. e.g.:

您考虑的任何模板语言都应满足这一问题。例如:

{$code_gets_escaped} 
{{$code_gets_escaped_as_a_uri}}
{{{$dangerous_bare_code}}}

This way, your potential doorways for exploitation are easily discernible in the template, as opposed to the doorway to exploitation being the DEFAULTbehaviour.

这样,您的潜在漏洞利用在模板中很容易识别,而不是利用漏洞利用默认行为。

回答by bobince

-1 for the typical hysterical ‘use [my favourite templating system] instead!' posts. Every PHP post, even if the native PHP answer is a one-liner, always degenerates into this, just as every one-liner JavaScript question ends up full of ‘use [my favourite framework] instead!'. It's embarrassing.

-1 对于典型的歇斯底里的“使用 [我最喜欢的模板系统] 代替!” 职位。每个 PHP 帖子,即使原生 PHP 答案是单行的,也总是退化为这一点,就像每个单行 JavaScript 问题最终都充满了“改用 [我最喜欢的框架]!”一样。这让人很难堪。

Seriously, we knowabout separating business logic and presentation concerns. You can do that?—?or notdo that?—?in any templating system, whether PHP, Smarty or something completely different. No templating system magically separates your concerns without a bunch of thinking.

说真的,我们知道分离业务逻辑和表示问题。您可以这样做吗?—?或这样做?—?在任何模板系统中,无论是 PHP、Smarty 还是完全不同的东西。没有任何模板系统可以在不经过大量思考的情况下神奇地将您的关注点分开。

(In fact a templating system that is too restrictive can end up with you having to write auxiliary code that is purely presentational, cluttering up your business logic with presentational concerns. This is not a win!)

(事实上​​,限制性太强的模板系统最终可能导致您不得不编写纯粹展示性的辅助代码,从而使您的业务逻辑因展示性问题而变得混乱。这不是一场胜利!)

To answer the question that was asked, the first example is OK, but very difficult to read due to the bad indentation. See monzee's example for a more readable way; you can use the : notation or {}s, whichever you prefer, but the important thing for readability is to keep your HTML and PHP as a single, ‘well-formed' indented hierarchy.

要回答提出的问题,第一个示例还可以,但由于缩进不好而很难阅读。有关更易读的方式,请参阅 monzee 的示例;您可以使用 : 表示法或 {} ,无论您喜欢哪个,但对于可读性而言,重要的是将您的 HTML 和 PHP 保持为单一的、“格式良好”的缩进层次结构。

And a final plea: remember htmlspecialchars(). Every time plain text needs to go in to a web page, this mustbe used, or it's XSS all over the floor. I know this question isn't directly related to that, but every time we post example code including < ?php echo($title) ?> or a framework equivalent without the escaping, we're encouraging the continuation of the security disaster area that most PHP apps have become.

最后一个请求:记住 htmlspecialchars()。每次需要纯文本进入网页时,都必须使用它,否则就是XSS。我知道这个问题与此没有直接关系,但是每次我们发布示例代码包括 < ?php echo($title) ?> 或没有转义的等效框架时,我们都鼓励继续存在安全灾区大多数 PHP 应用程序已经成为。

回答by Ken

The most important consideration is keeping the logic separate from the presentation - less coupling will make future changes to both much more straightforward.

最重要的考虑是将逻辑与表示分开 - 更少的耦合将使未来对两者的更改更加直接。

You might even want to consider using some sort of templating system like smarty.

您甚至可能想考虑使用某种模板系统,如smarty

回答by monzee

For a very simple case like this, it is fine to use PHP as a template. However, if you go beyond simple logic (and you most likely will), it is a good idea to use template engines.

对于这种非常简单的情况,使用 PHP 作为模板就可以了。但是,如果您超越了简单的逻辑(并且您很可能会),那么使用模板引擎是个好主意。

In Zend Framework, which uses PHP view scripts by default, the recommended way to do this would be like this:

在 Zend Framework 中,它默认使用 PHP 视图脚本,推荐的方法是这样的:

<?php if ($a) : ?>
    [MARKUP HERE]
<?php else : ?>
    [SOME MORE MARKUP]
<?php endif ?>

The more verbose syntax makes it a lot easier to match conditional blocks in a glance than using braces.

与使用大括号相比,更冗长的语法使得一目了然地匹配条件块要容易得多。

回答by Treb

It is better to completely seperate your logic (PHP code) from the presentation (HTML), by using a template engine.

最好使用模板引擎将您的逻辑(PHP 代码)与演示文稿(HTML)完全分开。

It is fast and easy to insert PHP into HTML, but it gets messy very fast, and is very difficult to maintain. It is a veryquick and verydirty approach...

将 PHP 插入 HTML 既快速又容易,但很快就会变得混乱,并且很难维护。这是一种非常快速且非常肮脏的方法......

As for which of all the template engines available in PHP is better, see these questions for example:

至于 PHP 中可用的所有模板引擎中哪个更好,请参见这些问题,例如:

回答by neu242

If a template engine seems to much of a hassle you can make your own poor man's template engine. This example should definately be improved and is not suitable for all tasks, but for smaller sites might be suitable. Just to get you an idea:

如果模板引擎看起来很麻烦,您可以制作自己的穷人模板引擎。这个例子肯定应该改进,并不适合所有任务,但对于较小的站点可能是合适的。只是为了给你一个想法:

template.inc:

模板.inc:

<html><head><title>%title%</title></head><body>
%mainbody%
Bla bla bla <a href="%linkurl%">%linkname%</a>.
</body></html>

index.php:

索引.php:

<?php
$title = getTitle();
$mainbody = getMainBody();
$linkurl = getLinkUrl();
$linkname = getLinkName();
$search = array("/%title%/", "/%mainbody%/", "/%linkurl%/", "/%linkname%/");
$replace = array($title, $mainbody, $linkurl, $linkname);
$template = file_get_contents("template.inc");
print preg_replace($search, $replace, $template);
?>

回答by Jeremy Weathers

Neither. Use Smarty. By separating your internal logic from the display logic you will build code that is much simpler to maintain. (Don't take the path of PHPLib's old template system that tried to completely separate PHP and HTML - it requires display logic to be intermingled with your core business logic and is very messy.) If you absolutely must generate HTML snippets in your PHP code, use your 2nd method, but pass the variable to Smarty.

两者都不。使用Smarty。通过将内部逻辑与显示逻辑分离,您将构建更易于维护的代码。(不要走 PHPLib 的旧模板系统试图将 PHP 和 HTML 完全分离的路径 - 它需要显示逻辑与您的核心业务逻辑混合并且非常混乱。)如果您绝对必须在您的 PHP 代码中生成 HTML 片段,使用您的第二种方法,但将变量传递给 Smarty。

回答by Jeremy Weathers

Something I wish I'd known when I first started doing PHP: Keep your heavy-lifting program code as far away from your HTML output as possible. That way they both stay in large, fairly contiguous, readable chunks.

我希望在我第一次开始使用 PHP 时就知道:让繁重的程序代码尽可能远离 HTML 输出。这样它们都保持在大的、相当连续的、可读的块中。

The best way I've found of doing this is to make a static HTML file first, maybe with some fake data so I can poke around and get the design right, then write PHP code to get the dynamic part of the output and glue them both together (how you do that part is up to you - you could do it with Smarty like others are suggesting).

我发现这样做的最好办法是让静态HTML文件首先,也许有一些假的数据,所以我可以闲逛,并获得设计权,然后编写PHP代码来获取输出的动态部分和胶水他们两者结合在一起(你如何做这部分取决于你 - 你可以像其他人建议的那样用 Smarty 来做)。

回答by PartialOrder

If you mustdo it either way use the curly braces. Don't echo HTML with PHP.

如果你必须这样做,请使用花括号。不要用 PHP 回显 HTML。

回答by markus

Smarty is ok, if you're not using a framework or when you're using a framework which doesn't have it's own templating system.

Smarty 没问题,如果您不使用框架或使用的框架没有自己的模板系统。

Otherwise most PHP frameworks and younger generation CMS have their own templating system.

否则大多数 PHP 框架和年轻一代的 CMS 都有自己的模板系统。

In general the idea of a templating system is to have files which contain almost only HTML (View/Template File) and files which contain only data or business logics (Model or Controller Files).

一般来说,模板系统的想法是拥有几乎只包含 HTML(视图/模板文件)的文件和只包含数据或业务逻辑(模型或控制器文件)的文件。

A Template File can look something like this (example from SilverStripe):

模板文件看起来像这样(来自 SilverStripe 的示例):

<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head>
        <% base_tag %>
        $MetaTags
        <link rel="stylesheet" type="text/css" href="tutorial/css/layout.css" />
    </head>
    <body>
        <div id="Main">
            <ul id="Menu1">
                <% control Menu(1) %>
                <li class="$LinkingMode">
                    <a href="$Link" title="Go to the &quot;{$Title}&quot; page">$MenuTitle</a>
                </li>
                <% end_control %>
            </ul>
            <div id="Header">
                <h1>$Title</h1>
            </div>
            <div id="ContentContainer">
                $Layout
            </div>
            <div id="Footer">
                <span>Some Text</span>
            </div>
        </div>
     </body>
</html>

You can see that there are only a few non-HTML code pieces inserted in the places where data will be inserted before the page is sent to the client.

您可以看到,在将页面发送到客户端之前,在将要插入数据的地方只插入了一些非 HTML 代码段。

Your code can then (simplified) rather look something like:

然后,您的代码可以(简化)看起来像:

<?php
  unset($out);
  if($a) $out = '[SOME CONTENT TO INSERT INTO THE TEMPLATE]';
  else $out = '[SOME ALTERNATIVE CONTENT]';
  templateInsert($out);
?>

The great thing about it: Your HTML can be seen as such and changed as such, your designer can make sense of it and doesn't have to look through your code trying to get the bits and pieces together from different places without any chance to view what she's doing. You on the other hand can make changes in the logic without worries about how it will look on the page. You'll most probably also make less mistakes because your code will be compact and therfore readable.

关于它的伟大之处:您的 HTML 可以被这样看待和改变,您的设计师可以理解它,而不必查看您的代码,试图将来自不同地方的零碎拼凑在一起,而没有任何机会看看她在做什么。另一方面,您可以更改逻辑,而无需担心它在页面上的外观。您也很可能会犯更少的错误,因为您的代码将很紧凑,因此具有可读性。