yarek
yarek

Reputation: 12054

php: how to replace all string values by variables values?

I am using that kind of html template:

Hello {{username}}, my email is {{email}} and my age is {{age}}

(number of {{variables}} is dynamic)

I would like to autoamtically parse the template and replace all {{variables}} by their php variable content

ex:

$username="Peter"; $email="myemail";$age=20;

so it should render like :

$res = render("template.html", array("username"=>$username, email=>$email, age=>$age));

Hello Peter; my email is myemail and my age is 20

Upvotes: 0

Views: 451

Answers (2)

Clay
Clay

Reputation: 4760

You could do it like this:

function render($template, $vars) {
    $template = file_get_contents($template);
    $search  = [];
    $replace = [];
    foreach ($vars as $key => $value) {
        $search[] = '{{'.$key.'}}';
        $replace[] = $value;
    }
    return str_replace($search, $replace, $template);
}

Although if you want more complexity you should use something like Handlebars:

https://github.com/zordius/lightncandy

https://github.com/XaminProject/handlebars.php

etc

Upvotes: 2

joshua pogi 28
joshua pogi 28

Reputation: 532

Try this.

function render($template,$values){
    $data=file_get_contents('templates/'.$templates); //templates/ is just templates path. you can change it.

    foreach ($values as $key => $value) {
        $data=str_replace('{{'.$key.'}}', $value, $data);
    }

    return $data;
}

Upvotes: 0

Related Questions