PHP Templating in Just PHP

Programming - Mar 31, 2024

With stuff like template literals in JavaScript and templating languages, like JSX, I’ve gotten used to wanting to write my HTML templates in one nice chunk and sprinkling in variables wherever I need them.

I had a situation where I needed to do that in “raw” PHP the other day, so I’m just documenting it here.

Say I have some data like…

$title = "The Title";
$desc  = "Some information about this thing blah blah.";
$img   = "/images/header.jpg";

But that data changes, or there might be multiple sets of it, and I want to be able to pass that data into a function and have it spit out some HTML. That way, it’s easy to change the template and have it affect everywhere that uses it.

I don’t want to sprinkle it into some HTML as a one-off. I’d rather have a function.

function echo_card($title = "Default Title", $desc = "Default Description", $img = "/images/fallback.jpg") {
   echo "";

Rather than string-interpolate a bunch of HTML together, PHP has the HEREDOC syntax that is a smidge like JavaScript’s template literals.

function echo_card($title = "Default Title", $desc = "Default Description", $img = "/images/fallback.jpg") {
   $html = <<<"EOT"
      <div class="card">
         <img src="$img" alt="">

   echo $html;

Now I can call this function to echo an HTML template with my data.

echo_card($title, $desc, $img);

I found it a fairly comfortable way to work, without requiring any other libraries or anything.

Previous Next
We respect the property rights of others, and are always careful not to infringe on their rights, so authors and publishing houses have the right to demand that an article or book download link be removed from the site. If you find an article or book of yours and do not agree to the posting of a download link, or you have a suggestion or complaint, write to us through the Contact Us .
Read More