0

I notice most (if not all) templates are written in HTML with PHP snippets where required.

I've been writing a few PHP heavy templates, and instead of writing HTML and encasing almost every line in tags, I have opted for writing PHP, using the print function to render HTML.

Is there any reason I should be writing in mostly HTML instead?

I imagine there's more overhead using PHP to render the HTML, but is there enough to worry about?

Second to that, is there any reason templates encase every line in tags instead of just the opening and closing tags are required?

e.g.

<?php if($a == $b) {?>
   <?php print 'a equals b';?>
<?php } else {?>
   <?php print 'a does not equal b';?>
<?php } endif;?>

vs

<?php if($a == $b) {
   print 'a equals b';
 } else {
   print 'a does not equal b';
 } endif;?>

1 Answer 1

1

Overhead, if there is any, is of little concern. This is pretty much a stylistic concern. As such, the important part is a consensus among developers so there is clear readability expectations.

drupal.org has documentation when it comes to template coding standards. In this case, little-as-possible PHP tags usage is preferred (the concern here is readable HTML rendering, not code execution) with use of PHP's alternative control structure:

<?php if ($a == $b):?>
   a equals b
<?php else: ?>
   a does not equal b
<?php endif; ?>

See the documentation for further style guidelines with templates.

1
  • Thanks Shawn. Some good pointers in the documentation. It's good to know I'm not so much as doing something wrong - more that I could be doing something better. It's interesting a lot of templates don't seem to follow the "little-as-possible PHP tags" rule.
    – Simo
    Sep 20, 2016 at 22:24

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.