Keeping HTML files separated from the PHP files (template based)

后端 未结 5 1715
情歌与酒
情歌与酒 2021-01-26 00:51

I am trying to keep all the PHP files separated from the HTML files. Sort of a template based project but without using any template engines as they ar

5条回答
  •  情深已故
    2021-01-26 01:31

    I would suggest using a template system to parse your template file.

    Just something quick and dirty:

    class Example {
        // This will be used to save all the variables set trough the set() function within the class as an array
        private $variables = array();
    
        function set($name,$value) {
                    // Here we are going to put the key and value in the variables array
            $this->variables[$name] = $value;
        }
    
        function Template($file) {
            // First set the file path of the template, the filename comes from the Template({filename}) function.
            $file = '/templates/'.$file.'.php';
    
            // Here we are going to extract our array, every key will be a variable from here!
            extract($this->variables);
    
            // Check if it is actually a file
            if (!is_file($file)) {
                throw new Exception("$file not found");
            // Check if the file is readable
            } elseif(!is_readable($file)) {
                throw new Exception("No access to $file");
            } else {
            // if both are fine we are going to include the template file :)
                include($file);
            }
        }
    }
    

    and use it like this:

    $class = new Example;
    $class->set("data", $data);
    // like passing a name:
    $class->set("user", $username);
    $class->Template("filename");
    

    Then in your template file you can use $data and $user with their contents.

    Also, in your template file you're not displaying the variable because it's not in between of PHP tags. Here's two examples for you, one short and the other in the normal format:

    
    // or :
    
    

    Oh, and you actually do nothing here:

    while (mysqli_stmt_fetch($stmt)) {
            $product_list .= "
    
    }
    }
    

    You NEED to close the opening " with "; and nothing is added to $product_list.

提交回复
热议问题