Replacing {{string}} within php file

前端 未结 6 2095
栀梦
栀梦 2020-12-08 17:08

I\'m including a file in one of my class methods, and in that file has html + php code. I return a string in that code. I explicitly wrote {{newsletter}} and th

6条回答
  •  离开以前
    2020-12-08 17:32

    Use output_buffers together with PHP-variables. It's far more secure, compatible and reusable.

    function template($file, $vars=array()) {
        if(file_exists($file)){
            // Make variables from the array easily accessible in the view
            extract($vars);
            // Start collecting output in a buffer
            ob_start();
            require($file);
            // Get the contents of the buffer
            $applied_template = ob_get_contents();
            // Flush the buffer
            ob_end_clean();
            return $applied_template;
        }
    }
    
    $final_newsletter = template('letter.php', array('newsletter'=>'The letter...'));
    

提交回复
热议问题