Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
426 views
in Technique[技术] by (71.8m points)

variables - Replacing {{string}} within php file

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 then in my method I did the following:

$contactStr = include 'templates/contact.php';
$contactStr = str_replace("{{newsletter}}",$newsletterStr,$contactStr);

However, it's not replacing the string. The only reason I'm doing this is because when I try to pass the variable to the included file it doesn't seem to recognize it.

$newsletterStr = 'some value';
$contactStr = include 'templates/contact.php';

So, how do I implement the string replacement method?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

<?php echo $newsletter; ?>

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...