PHP通用模板在树枝上。 如何重用代码?
I'm very new to PHP. I have a several of sites in which the only difference is a token. I use twig templating
. How can I refactor my code to don't repeat myself and make a code more correct? I assume there is a way in twig
to create a base template and reuse that. How should it look in my case?
My file:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../web/assets/css/error-templates.css">
</head>
<body>
<img class="logo" src="/assets/img/logo.png">
<div class="container">
<div class="wrap">
{# The only different is token below #}
::CLOUDFLARE_ERROR_500S_BOX::
</div>
</div>
</body>
</html>
Another file:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../web/assets/css/error-templates.css">
</head>
<body>
<img class="logo" src="/assets/img/logo.png">
<div class="container">
<div class="wrap">
{# The only different is token below #}
::ALWAYS_ONLINE_NO_COPY_BOX::
</div>
</div>
</body>
</html>
我是PHP的新手。 我有几个网站,其中唯一的区别是令牌。 我使用 我的文件: p>
另一个文件: p>
twig templating code>。 我怎样才能重构我的代码,不重复自己并使代码更正确? 我假设在
twig code>中有一种方法可以创建一个基本模板并重用它。 它应该如何看待我的情况? p>
&lt;!DOCTYPE html&gt;
&lt; html&gt;
&lt; head&gt;
&lt; link rel =“stylesheet”type =“text / css”href =“../ web / assets / css / error-templates.css”&gt;
&lt; / head&gt;
&lt; body&gt;
&lt; img class =“logo”src =“/ assets / img / logo.png”&gt;
&lt; div class =“container”&gt;
&lt; div class =“wrap”&gt;
{#唯一不同的是下面的标记#}
:: CLOUDFLARE_ERROR_500S_BOX ::
&lt; / div&gt;
&lt; / div&gt;
&lt; / body&gt;
&lt; / html&gt;
code > pre>
&lt;!DOCTYPE html&gt;
&lt; html&gt;
&lt; head&gt;
&lt; link rel =“stylesheet”type =“text / css”href =“../ web / assets / css / error-templates.css”&gt;
&lt; / head&gt;
&lt; body&gt;
&lt; img class = “logo”src =“/ assets / img / logo.png”&gt;
&lt; div class =“container”&gt;
&lt; div class =“wrap”&gt;
{#唯一不同的是下面的标记#}
:: ALWAYS_ONLINE_NO_COPY_BOX ::
&lt; / div&gt;
&lt; / div&gt;
&lt; / body&gt;
&lt; / html&gt;
code > pre>
div>
Create a master template file with twig extension (eg. main.twig) containing below:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../web/assets/css/error-templates.css">
</head>
<body>
<img class="logo" src="/assets/img/logo.png">
<div class="container">
<div class="wrap">
{% block BodyMain %}{% endblock %}
</div>
</div>
</body>
</html>
and in your other pages, use the code below
{% extends "main" %}
{%block BodyMain %}
::ALWAYS_ONLINE_NO_COPY_BOX::
{% endblock %}
See reference twig extends documentation