janpio
janpio

Reputation: 10912

Correct way to reference image from asset folder in a Markdown document (that works both rendered locally and via Jekyll)?

What is the correct way, in a Markdown document, to reference images that are stored in the /asset folder, so they can be rendered locally (Visual Studio Code) but also deployed in a Jekyll site?

Right now I include my images like this:

![alt text]({{ site.url }}/assets/image.png)

This works only when the site is rendered with Jekyll and if site.url is correctly set, which means that _config.yml has to be changed depending on the location the Jekyll project is deployed (on root of domain vs. in subfolder).

But this does not work at all if I render the document in e.g. Visual Studio Code. There I haev this option:

![alt text](/assets/image.png)

which will of course not work when deployed with Jekyll in a subfolder.

Or I can use a fully relative reference:

![alt text](../assets/image.png)

which is very impractical as image paths depend on where I have my content files. Moving a file from one folder to another changes the image URL.

Is there a way to make both Jekyl and local rendering (e.g. Visual Studio Code) work?

Upvotes: 2

Views: 2947

Answers (1)

marcanuy
marcanuy

Reputation: 23982

The following way misses the baseurl, i.e. it doesn't handle subdirectories:

 ![alt text]({{ site.url }}/assets/image.png)

To fix that, have baseurl in _config.yml and use it in your links:

![alt text]({{ site.url }}/{{site.baseurl}}/assets/image.png)

Even better, use absolute_url that will include url and baseurl generating full paths:

![alt text]({{"/assets/image.png" | absolute_url}})

Update

As discussed in comments, the above solution won't work in VSCode but having images with relative paths does.

So putting the mages in each post/collection folder and loading them with relative paths should make VSCode able to render images in each file - while also keeping Jekyll happy and render the image as it should.

Upvotes: 3

Related Questions