0

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

4
  • 2
    Have you considered using something like Twig instead of reinventing the wheel? ;) Commented Dec 10, 2015 at 10:52
  • This task would be solved much easier and more elegant by means of a HEREDOC definition, but the syntax for your template would have to be slighty different: php.net/manual/en/… Commented Dec 10, 2015 at 10:52
  • how about using <?=$username?> instead of {{username}} ? Commented Dec 10, 2015 at 10:53
  • you can consider replacing all '{{' with '$' and '}}' with ''. If you are using vim editor try this: :%s/{{/$/gc :%s/}}//gc Commented Dec 10, 2015 at 10:54

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.