I have seen in some scripts, where they use {{}} to echo inside HTML, and I think it looks way more clean!
So, for example I now have:
<?php $hi = "hello"; ?>
<html>
<title><?php echo $hi; ?></title>
and that will display hello in the title, but what I would like to have is:
<?php $hi = "hello"; ?>
<html>
<title>{{hi}}</title>
How can I do this?
What you have probably seen it was a template engine, have a look at twig here : http://twig.sensiolabs.org/
Here's the documentation: http://twig.sensiolabs.org/documentation
Here's how you can install it : http://twig.sensiolabs.org/doc/intro.html#installation
Or AngularJS:
Here's a link: https://angularjs.org/
In PHP, you cannot get the variable name (unless using unreliable hacky methods). But as @samayo mentioned, this is usually handled by a template engine.
If you want to mange this yourself, you can do the following:
$array = [
'tag' => 'a',
'text' => 'b'
];
$html = '<html>
{{tag}}
<body>
{{text}}
</body>
</html>';
Now you can use a couple of methods to replace this, usually done by regex:
preg_match_all("/.*({{(.*)}})/", $html, $result);
Outputting:
$result = array(
0 => array(
0 => '{{tag}}'
1 => '{{text}}'
)
1 => array(
0 => '{{tag}}'
1 => '{{text}}'
)
2 => array(
0 => 'tag'
1 => 'text'
)
)
You could also directly replace the data with preg_replace()
With this, you have all the data you would need to replace text. $result[2][0]
is referring to $array[key]
($array[$result[2][0]]
))replacement definition. This is how template engines usually work.
I have used [Dust.js] (www.dustjs.com) successfully like templating javascript engine in my PHP project. Dustjs is good framework mainly if you need some resources from REST sources using JSON. DustJs is designed to run asynchronously on both the server and the client browser. At this time is have choosed the last option. DustJs can use Partials - Templates that can include other templates.
Dustjs has ability to navigate onto your JSON structure looping and searching KEYS to get data simplifying your rendering work and uncoupling your data of user interface.
DustJs is maintained by Linkedin Team and largely adopted on mainly site.
Give a try to him. Start on http://www.dustjs.com/guides/getting-started/.
Cheers.
use php frameworks that has a template engine
like laravel ( Blade templating engine )