开发者

Avoid repeated HTML

I have two HTML pages. I would like to avoid repeating markup, like head, navigation, etc. For example, here is one page:

<head><title>Los Pollos Hermanos</title></head>
<body>About Us</body>

And here is another:

<head><title>Los Pollos Hermanos</title></head>
<body>Contacts</body>

I don't like to repeat things, s开发者_StackOverflow社区o, I want to move the head+title part out, to some separate file, and then call this separate file from other pages. Is this the correct way? What is the practice?


It depends on the language you are using. If you want to do this strictly in HTML, see if your server supports shtml. If it does, you can use includes to read the file into another file.

<!--#include FILE="filename.html"--> 


Use a template language. The specific one you choose will depend on what your server supports and your personal preferences.

All else being equal, I would use Template Toolkit since it can be used by itself at build time (i.e. before you upload it and with no need for the server to support anything beyond static files) thanks to ttree and can be used at runtime from Perl.

There is a good introductory tutorial for using TT to generate web content.


you can't directly from html, but it's pretty simple if you're using php or asp or something like that to generate the html. check for include if php, for example


You can place your common code in a .tpl file and include that link in the page. For example

<!--#include virtual="../_tpl/header.tpl" --> 
 <div class="content">

  some code goes here...

</div>

and in header template you place all your common code like

<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>PAGETITLE</title>
    <meta name="Keywords" content="" />
    <meta name="Description" content="" />
    <meta http-equiv="Content-Style-Type" content="text/css" />
    <meta http-equiv="Content-Script-Type" content="text/javascript" />


    <link rel="stylesheet" type="text/css" media="all" href="..." />

    <script type="text/javascript" src="....."></script>

</head>


A classic approach is to have a layout that contains footer and header. Then you decorate your pages with your layout like this:

_________layout________
|  ________________   |
|  |    header     |  |
|  |_______________|  |
|  _________________  |
|  |               |  |
|  |  specific     |  |
|  |    page       |  |
|  |               |  |
|  |_______________|  |
|  ________________   |
|  |    footer     |  |
|  |_______________|  |
|_____________________|

This is what most web frameworks do.


In ASP.Net you can use what's called a Master Page. In ASP.Net MVC, a similar concept using Layout pages. You define all this content in the master, and set a tag showing where the "changing" content would show up. Then other files (pages) define what shows in those defined spots in the template.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜