Best practice for HTML head in PHP

前端 未结 4 2201
不思量自难忘°
不思量自难忘° 2021-01-01 22:36

I currently have a very simple page, with some more complicated backend. I\'ve always done this the same way, but I feel it\'s not right. But I haven\'t come up with much us

4条回答
  •  北海茫月
    2021-01-01 23:07

    Methinks that you are looking for templates.

    Though you almost nailed it, you are mixing matters a little. Just separate your "design parts" from "code parts". Don't make header to do the job of the actual code and everything become as clear as a fresh water

    Let me suggest you the following setup:
    A site contains of

    • main config file (suppose it's something like your functions.php)
    • main site template
    • actual pages (or sections) - actual php scripts of different purpose. Each consists of 2 parts:
      • script itself, doing all data mining and preparations, initialising all variables
      • a template, doing the job of data output only.

    the main idea is to make PHP script do no output until all data got ready - thus you will get an instant solution of your page title problem. Moreover (think about it):

    • you will be able to send whatever HTTP headers, cookies, start session etc.
    • you will be also able to change whole output appearance on the fly: an XML or JSON instead of HTML for example
    • you will be able to use the same code base for the different sites, changing only templates

    Once php script done with data preparations, it calls for the the main site timplate, which, in turn, will include the actual page template.

    Thus you will get exactly what you're asking for - the website dynamic enough that it can have easily editable pages, but also be easily editable is a big part of it needs editing - and many more other benefits.

    Template I am talking about is a typical PHP script, however, consists mostly of pure HTML, with some PHP code only to display dynamically generated data.

    Here you go with some basic yet working example

    the page:

    
    

    where main.tpl.php is your main site template, including common parts, like header, footer, menu etc:

    
    
    My site. <?=$pagetitle?>
    
    
    

    and links.tpl.php is the actual page template:

提交回复
热议问题