简体   繁体   中英

How to attach code from one html file into another?

So I've been trying to figure out an easy way to update every html page.

The idea is to have one html file that holds specific code - in this case, a simple list with some href bits on it.

Then have the other html files call the first document's code.

I have not been able to find a valid solution for this issue -- but I think that's due to not being able to word it correctly for searching.

Thanks, -Zen

It sounds like you're looking for a web server/framework stack. A web server would run your application, which in turn would execute code to combine/assemble HTML and serve it to the user. If you were using PHP, you'd have, for instance, a layout.phtml file:

<!doctype html>
<html>
    <head></head>
    <body>
        <?php 
            echo $this->getContent('content.phtml');
        ?>
    </body>
</html>

And a content file, content.phtml:

<p>Some content</p>

Your web app would look at the layout file, see that you want to plug in the DOM from content.phtml, fetch that DOM and render it within the layout.phtml. It would then serve the combined version to the user.

Some common web frameworks: Light: Express on Node.js, Sinatra on Ruby Heavy: Ruby on Rails, Zend Framework on PHP, Django on Python

If you're looking for a sandbox to host your web app, or a service to take care of server administration for you, check out Heroku.

You can use either

include 'filename'; 

or

require 'filename';

The difference is that require will produce a fatal error (E_COMPILE_ERROR) and stop the script. include will only produce a warning (E_WARNING) and the script will continue.

To use them, your file has to be in .php format.

.php file can contain html contents alone. There is no restriction that it has to contain only php code.

For example:

Index.php

<?php
require 'page2.php';
?>
<html>
<head>
<title>Page 1</title>
</head>
<body>
<hr><h1>Page 1 Content</h1>
</body>
</html>

page2.php

<html>
<body>
<hr><h1>Page 2 Content</h1>
</body>
</html>

You can also use jQuery

index.html

<html> 
<head> 
<script src="jquery.js"></script> 
<script> 
$(function(){
$("#includedContent").load("page2.html"); 
});
</script> 
</head> 
<body> 
<div id="includedContent"></div>
</body> 

page2.html

<html>
<body>
<hr><h1>Page 2 Content</h1>
</body>
</html>

Hope it helps

Simple solution!

First of all rename all of your .html files to .php files

Then whenever you want to use another pages html, you just type the following line!

<?php include_once "path/to/file.php" ?>

Tada!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM