Absolutizing an image url with a ".."

258 Views Asked by At

I have an HTML document I'm transforming with an image whose source url looks like this:

"../foo/bar/baz.png"

I'm using a tritium function to absolutize image source urls, but the ".." seems to be stumping it. It's prepending the hostname, etc, but when it does, it adds one too many layers.

So for example, the correct URL of the image is:

"www.host.com/foo/bar.png"

But the page on which it appears is at "www.host.com/site/baz/page.html"

The source of the image in the original html is therefore "../foo/bar.png"

But the absolutized result I'm getting is: "www.host.com/site/foo/bar.png"

In other words it's going up the file tree to "/site/", but it needs to be going up one more. I don't really see how it even works on the original page without another ".." How should I be handling the ".." in the url?

3

There are 3 best solutions below

1
On BEST ANSWER

As you're in a Moovweb project, I would suggest manipulating the problematic src before you use the absolutize() function.

Is there an easy way you can select the image using Tritium? I'd suggest doing that, then manipulating the src attribute:

$("./img[@id='']") {
  attribute("src", "/foo/bar.png")
}

After this, you should be able to use the absolutize() function and the src will be rendered correctly.

0
On

.. means to traverse one level up; you are using a relative path, not an absolute one like you should be. Drop the dots:

<img src="/foo/bar.png"> will load the image from the root of the domain.

0
On

There is a huge difference between src="/foo/bar.png" and src="foo/bar.png" (Notice the slash after the first double quote)

First one points to http://example.com/foo/bar.png NO MATTER what.
Second one, however, (without the beginning slash) is relative URL so the output path depends on the file on which the image appears.

That is why you were getting "www.host.com/site/foo/bar.png" (one level up relative to the file path).

Two solutions:
1) src="/foo/bar.png" OR
2) src="../../foo/bar.png"

I always recommend the first approach because even after you move the files around, you won't have to change the absolute URL. (I learned it the hard way)

P.S. this rule applies to CSS files as well. (for example when specifying the background image URL) If you use absolute paths, you won't have to bang your head on the wall when you change the directory of the CSS file.