Reputation: 65
I have several static HTML pages containing a set of links within a div
. Currently, when I edit this set of links, I have to make the same edit on multiple pages.
Is there an easier way to update the div
on every page when I make a change? Perhaps I could move it to a separate HTML file and insert it using jQuery?
Upvotes: 2
Views: 2965
Reputation: 16499
Say you have your links in a static file in the root folder of your website called links.html:
<div id="links">
Your links.
</div>
There are a few ways you can include this file in another page; here are three of the easiest.
It is trivially easy using jQuery.load
.
JS:
$('.add-links').load('/links.html');
HTML:
<div class="add-links"></div>
First, enable SSI on your server if it isn't already. (E.g. here's how you set up SSI in Apache, IIS6 and IIS7.) Next, add the include where it needs to be in your static file.
HTML:
<!--#include virtual="/links.html" -->
Assuming PHP is correctly installed and enabled, tell the server to parse your static HTML files as PHP—e.g. by changing the extensions from .html
to .php
. You can include the links where they need to appear as follows:
<?php include('/links.html'); ?>
Upvotes: 0
Reputation: 6736
you can do it using PHP
<div>link</div>
save this div as separate file. and then include this file include('filepath');
on every page. so when you want edit you just have to edit once in main file.
Upvotes: 0
Reputation: 6381
well, what you actually need (if you want to stay with Javascript, no PHP) is templating (I can recommend you mustache.js)
then, your code will look like this:
var data = {
links: [
{ url: "http://",
text: "Lorem"},
{ url: "http://",
text: "Ipsum"}
]};
var template = "<ul>{{#links}}" +
"<li><a href="{{url}}">{{text}}</a></li>" +
"{{/links}}</ul>";
var html = Mustache.to_html(template, data);
$('#DIV_CONTAINING_MENU').html(html);
of course, you can do the same with jQuery (and even javascript):
var data = [
{url: 'http://', text: 'Lorem'},
{url: 'http://', text: 'Ipsum'}
];
$ul = $('<ul></ul>');
for(var i=0,c=data.length;i<c;i++){
$ul.append('<li><a href="'+data[i].url+'">'+data[i].text+'</a></li>');
}
$ul.appendTo($('#DIV_CONTAINING_MENU'));
Upvotes: 2