2

I'm wanting to create a website with common headers and footers for each webpage and am currently using the answer supplied here.

However, I have a website with a tree diagram similar to:

- index.html
- header.html
- footer.html
- folder
    - info.html

In my header and footer files, there are multiple (relative) links such as to image sources, other pages, etc, which means while they may work in index.html, if I try to load it into info.html, the links break.

Is there any way to change all links to look one folder back, etc, or would I have to use javascript to change the src property for every referenced image?

Ciaran
  • 35
  • 1
  • 5
  • May I see your code? – Ehsan Sepehri Jul 04 '20 at 05:49
  • If you use *root relative* paths you can avoid this issue also. A leading `/` tells browser to start at root of site. So if you have an `images` folder the path `/images/someImage.jpg` will work the same in your `folder/info.html` as it will in `index.html` – charlietfl Jul 04 '20 at 05:49

3 Answers3

2

Add the <base> element to your info.html and make its href tallying the relative links of your header and footer markups.

For example, if your website is hosted in http://example.com/foo and your relative links are such as ./images/xyz.jpg, the base element of the info.html would be like this:

<base href="http://example.com/foo">

The browser will compose the relative urls from there.


Another option is to configure your relative urls to pick up resources from the root.

In above configuration, instead of this:

<img src="./images/xyz.jpg">

...you can use

<img src="/foo/images/xyz.jpg">

So, wherever it is executed from, browsers will start the relative paths from the root.

The advantage is that this will enable easy local testing too.

Charlie
  • 22,886
  • 11
  • 59
  • 90
2

You can use <base> tag in your info.html file's <head> tag with a href attribute.

The <base> tag specifies the base URL and target for all relative URLs in a document.

The <base> tag must have either an href or a target attribute present, or both.

There can only be one single <base> element in a document, and it must be inside the <head> element.

You can find more in this example.

Abhishek T.
  • 1,133
  • 1
  • 17
  • 33
1

This is basically what the <base> element is for. You include it in the document and specify an href from which all relative links/urls are resolved.

ray
  • 26,557
  • 5
  • 28
  • 27