Modify PHP. Customize how PHP calls a function

前端 未结 4 1084
终归单人心
终归单人心 2020-12-22 07:10

Can php be modified to create a custom way to call a php function without opening and closing php tags? For example, given an example function like this that is incl

4条回答
  •  庸人自扰
    2020-12-22 07:17

    Most of the time a fancy template engine is entirely unnecessary. You can easily accomplish this by running a simple str_replace loop of your tokens and their values over the otherwise-ready HTML (that you've stored into a variable) before you echo it all out. Here's what I do:

    $html = 'My-ready-HTML with {{foo}} and {{bar}} thingys.';
    
    // Or: $html = file_get_contents('my_template.html');
    
    $footsy = 'whatever';
    $barsie = 'some more';
    
    $tags = [
        'foo' => $footsy,
        'bar' => $barsie
        ];
    
    function do_tags($tags, $html) {    
        foreach ($tags as $key=>$val) {
            $html = str_replace('{{'.$key.'}}', $val, $html);
        }
        return $html;
    }
    
    $output = do_tags($tags, $html);
    
    echo $output;
    

提交回复
热议问题