Home > Mobile >  Most sensible approach to generate repeated HTML source. Use PHP?
Most sensible approach to generate repeated HTML source. Use PHP?

Time:01-10

Hi I was wondering what is a sensible approach to generating repeated HTML source code such as that below. Suppose I have, say, thirty, lines where the numbering goes from 1 to 30, say. And I have a number of such pages that need this structure. I had jumped to generating this code in the page itself using a PHP loop, as I'm using PHP anyway in the project.

My question is, is this a sensible approach? What is best practice in such cases? I'm not sure using PHP in the page to generate the HTML each time like this is wise. Or is it?

Thank you for any steer or advice.

<a href="images/mypic (1).jpg">
<img src="images/mypic (1).jpg" alt="Picture 1">
</a>

<a href="images/mypic (2).jpg">
<img src="images/mypic (2).jpg" alt="Picture 2">
</a>

etc..

CodePudding user response:

That's precisely the purpose of PHP : generating HTML code.

You can use a simple for loop :


<?php for($i=1; $i<=30; $i  ) : ?>
  <a href="images/mypic (<?= $i ?>).jpg">
    <img src="images/mypic (<?= $i ?>).jpg" alt="Picture <?= $i ?>">
  </a>
<?php endif; ?>

CodePudding user response:

Why not JS? That would transfer the least code from the server

document.body.innerHTML = Array.from({length:30})
  .map((_,i) => `<a href="images/mypic (${(i 1)}).jpg"><img src="images/mypic (${(i 1)}).jpg" alt="Picture ${(i 1)}"></a>`)
  .join('<br/>')

  • Related