doomm4711 2018-01-23 11:05
浏览 69
已采纳

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>
  • 写回答

1条回答 默认 最新

  • dswqz24846 2018-01-23 11:12
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?