Replacing {{string}} within php file

前端 未结 6 2120
栀梦
栀梦 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:31

    You can use PHP as template engine. No need for {{newsletter}} constructs.

    Say you output a variable $newsletter in your template file.

    // templates/contact.php
    
    
    

    To replace the variables do the following:

    $newsletter = 'Your content to replace';
    
    ob_start();        
    include('templates/contact.php');
    $contactStr = ob_get_clean();
    
    echo $contactStr;
    
    // $newsletter should be replaces by `Your content to replace`
    

    In this way you can build your own template engine.

    class Template
    {
        protected $_file;
        protected $_data = array();
    
        public function __construct($file = null)
        {
            $this->_file = $file;
        }
    
        public function set($key, $value)
        {
            $this->_data[$key] = $value;
            return $this;
        }
    
        public function render()
        {
            extract($this->_data);
            ob_start();
            include($this->_file);
            return ob_get_clean();
        }
    }
    
    // use it
    $template = new Template('templates/contact.php');
    $template->set('newsletter', 'Your content to replace');
    echo $template->render();
    

    The best thing about it: You can use conditional statements and loops (full PHP) in your template right away.

    Use this for better readability: https://www.php.net/manual/en/control-structures.alternative-syntax.php

提交回复
热议问题