nalzok
nalzok

Reputation: 16157

Cannot link to static files with Hugo

I have this in config.toml:

baseURL = "https://my-username.github.io/blog/"

and there is a static file at static/img/foo.png.

Now, in content/posts/bar.md, I have the following content:

---
title: "Bar"
---

![foo](img/foo.png)

The picture isn't showing after I started the hugo server, so I inspected elements, and found out that Hugo generated the following URL for it:

http://localhost:1313/blog/posts/bar/img/hireme.png

This is not what I expect; it should be

http://localhost:1313/blog/img/hireme.png

When I use ![foo](/blog/img/foo.png), the picture is displayed correctly, but this is quite strange: /blog/ is part of baseURL, why do I need to type it again?

Upvotes: 3

Views: 8626

Answers (2)

Scriptonomy
Scriptonomy

Reputation: 4055

In a simple setup where your site lives in the domain's root, a absolute reference to the image would be a standard practice. However, in your case where the site is nested, a more crafty solution is necessary.

I suggest using a shortcode to solve your dilemma. Just simply create a shortcode that takes in a resource file path and spits out the desired absolute path every time. The advantage to this approach is flexibility for future resource relocation to a cdn for example.

Your markdown code will be something like this: ![foo]({{< resource url="img/foo.png" >}})

Your shortcode template will be something like this: {{ .Site.BaseURL }}{{ .Get "url" }}

Create a file named 'resource.html' in 'layouts/shortcodes/' folder, and drop in the shortcode template code above.

So when you decide you want to switch to a cdn you could easily do this: ://cdn.example.com/{{ .Get "url" }}

Upvotes: 3

Dian
Dian

Reputation: 470

I think you should use <base> tag to make baseURL for static files.

Add the <base> tag into <head>:

<base href="{{ .Site.BaseURL }}">

And then you can insert image in post like this:

![Foo image](img/foo.jpg)

References:

Upvotes: 9

Related Questions