Skip to content Skip to sidebar Skip to footer

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 i

Solution 1:

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:

<?phpinclude('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:

<scriptsrc="jquery.js"></script><script> 
    $(function(){
      $("#includeThis").load("some_file_name.html"); 
    });
    </script> 
...
<divid="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.

Solution 2:

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:

<?phpinclude'navigation.html'?>

Solution 3:

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.

Post a Comment for "Can I Use Variables In Html?"