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 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作