John
John

Reputation: 13

Can I use variables in HTML?

I have 5 .html pages. I have the same navigation for each page. Is there any way I can set a variable somewhere that contains my navigation code, and then reference that variable in each of my documents?

I want to do this because if I ever want to edit my navigation, I can just go back and edit 1 source (the variable), as opposed to editing from each document.

Upvotes: 1

Views: 864

Answers (3)

MrMike
MrMike

Reputation: 1540

Pure HTML (without JavaScript) cannot load in another page on it's own. However, you can use PHP, SHTML, or JavaScript to obtain another page and load it into the page.

PHP

Make sure that your HTML file has been renamed with the .php extension. Then you can add the following line where you want to add the HTML file:

<?php include('some_file_name.html'); ?>

As long as some_file_name exists, that page will load in where the PHP tag is.

SHTML

Make sure that your HTML file has been renamed with the .shtml extension. Then you can add the following line where you want to add the HTML file:

<!--#include virtual="some_file_name.html" -->

Again, as long as some_file_name exists, the page will load in the page at that. Be sure to watch for spacing, especially between the second dash and #, as the line of code will break if there is a space.

JavaScript

The plus side of using JavaScript is that you can keep your HTML file a .html file. However, more code is needed to load in the included file:

<script src="jquery.js"></script> 
    <script> 
    $(function(){
      $("#includeThis").load("some_file_name.html"); 
    });
    </script> 
...
<div id="includeThis"></div>

This will create a function that will load some_file_name.html where the div id of includeThis is located. This contains more overhead, but you can keep your .html file extension.

Upvotes: 1

ElGavilan
ElGavilan

Reputation: 6914

You might want to look into using a server side scripting language like ASP.NET or PHP, or using templating (shtml), which have support for doing this on the server side. Alternatively you can use Javascript to do this on the client side, as one commenter showed above, but doing it server side is the most efficient way to do it.

Upvotes: 0

Pietro Coelho
Pietro Coelho

Reputation: 2072

yes, this is made with a server-side language like PHP. You would save your navigation in just one page, and in the main page just write:

 <?php include 'navigation.html' ?>

Upvotes: 1

Related Questions