Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is duplicate HTML represented in your codebase, in a non-duplicate way?

Tags:

php

codebase

Most HTML in a large website is duplicated across pages (the header, footer, navigation menus, etc.). How do you design your code so that all this duplicate HTML is not actually duplicated in your code? For example, if I want to change my navigation links from a <ul> to a <ol>, I'd like to make that change in just one file.

Here's how I've seen one particular codebase handle this problem. The code for every page looks like this:

print_top_html();

/* all the code/HTML for this particular page */

print_bottom_html();

But I feel uncomfortable with this approach (partially because opening tags aren't in the same file as their closing tags).

Is there a better way?

I mostly work with PHP sites, but I'd be interested in hearing solutions for other languages (I'm not sure if this question is language-agnostic).

like image 855
Steve Avatar asked Dec 29 '22 17:12

Steve


2 Answers

I'm not a php programmer, but I know we can use a templating system called Smarty that it works with templates(views), something like asp.net mvc does with Razor.

look here http://www.smarty.net/

like image 159
Cleiton Avatar answered Feb 15 '23 10:02

Cleiton


One solution at least in the case of PHP (and other programming languages) is templates. Instead of having two functions like you have above it would instead be a mix of HTML and PHP like this.

<html>
  <head>
   <title><?php print $page_title ?></title>
   <?php print $styles ?>
   <?php print $scripts ?>
  </head>

  <body>
    <div id="nav">
      <?php print $nav ?>
    </div>
    <div id="content">
      <?php print $content ?>
    </div>
  </body>
</html>

Each variable within this template would contain HTML that was produced by another template, HTML produced by a function, or also content from a database. There are a number of PHP template engines which operate in more or less this manner.

You create a template for HTML that you would generally use over and over again. Then to use it would be something like this.

<?php
  $vars['nav'] = _generate_nav();
  $vars['content'] = "This is the page content."
  extract($vars);  // Extracts variables from an array, see php.net docs
  include 'page_template.php'; // Or whatever you want to name your template

It's a pretty flexible way of doing things and one which a lot of frameworks and content management systems use.

like image 45
codeincarnate Avatar answered Feb 15 '23 10:02

codeincarnate