PHP templating without external dependencies
|Back in January, when I was learning php, I was quite disappointed to find out that there is no first-party templating engine. I did however stumble upon this stackoverflow post.
function simple_template() {
?>
<div>
<p>Hello World!</p>
</div>
<?php
}
At first you may wonder, what in God's name is going on here? Why are there php closing and opening tags inside of the function?
This method abuses the weird behaviours of inline html inside php.
Strictly speaking, it uses the fact that everything between the
<?php
?>
tags is saved by the interpreter and evaluated every time it's executed.
(this includes both the standard and
alternative
php syntax, allowing us to write inline php inside inline html)
Comparison with twig
Here is an easy example of how you would implement the simple thing of listing the users and their details in the twig templating engine from the Symfony framework.
<!-- list_users.twig -->
<ul class="users">
{% for user in users %}
<li>{{ user.name }}</li>
<li>{{ user.email }}</li>
<li>{{ user.phone_number }}</li>
{% endfor %}
</ul>
And here is how it could be implemented using the aforementioned tricks.
function list_users($data = Array()) {
?>
<ul class="users">
<?php foreach($data["users"] as $user): ?>
<li><?=$user["name"]?></li>
<li><?=$user["email"]?></li>
<li><?=$user["phone_number"]?></li>
<?php endfor ?>
</ul>
<?php
}
#
A Real life applications
Below is a code snippet from a file named core.php that houses
90% of the logic behind this website. This particular function is used for
abstracting away stuff that goes in the
<head>
tag.
function head($data = Array(), $data2 = Array()) {
$data = array_merge($data, $data2);
?>
<html lang="en">
<head>
<title><?=$data["title"]?></title>
<meta name="description" content="<?=$data["description"]?>">
<!-- ... -->
<?php if(in_array("highlighting", $data["enabled"])): ?>
<script src="/assets/js/prism.js"></script>
<!-- ... -->
<?php endif ?>
<?php if(in_array("comments", $data["enabled"])): ?>
<script defer>
var remark_config = { /* ... */ };
</script>
<?php endif ?>
</head>
<?php
}
(Full source code available here)
#Conclusions
Feel free to use this concept if you fancy so. I've chosen to use this out of spite for modern-day dependency neglect, but you can use this for any reason you want. If you've found this useful, you might wanna check out my other articles and let me know about any mistakes I've made here in the comments below.
< Previous |
Next > |