PHP Templating in Just PHP

Avatar of Chris Coyier
Chris Coyier on

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="">
         <h2>$title</h2>
         <p>$desc</p>
      </div>
EOT;

   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.