Dynamically embedding a local image based on a frontmatter property using DataviewJS

Hi all,

Dynamic embeds of local images is a common topic of forum and github threads, and there are a bunch of different approaches, but I’ve only recently discovered this approach, which I haven’t seen posted anywhere before. So hopefully this will be useful to some other people, as well. This solution is based on @holroy 's posts here.

Use case

  • You have multiple images stored within your vault
  • Your images have a consistent naming pattern
  • You want to use a frontmatter property to specify which image to embed within your note
  • You want the embedded image to update automatically if you update the frontmatter property

Requirements

  • You need to have dataview installed and both DataviewJS and inline JS enabled
  • Your frontmatter property value should be the same as the unique part of the image path

Code

 `$= dv.container = '<img src="' + app.vault.getResourcePath(dv.fileLink('Non/Unique/Image/Path/Here' + dv.current().FrontmatterPropertyHere + '.ExtensionHere')) + '" />' ` 

For example, if your images are stored in Attachments/Icons and are named Icon_Yellow.png and Icon_Blue.png, your frontmatter would be

---
Colour: Yellow
---

and your embed code would be

 `$= dv.container = '<img src="' + app.vault.getResourcePath(dv.fileLink('Attachments/Icons/Icon_' + dv.current().Colour + '.png')) + '" />' ` 

This appears to work cross-platform, and the embed updates pretty immediately after you’ve updated the frontmatter, although you may have to prompt a re-render, for example by toggling between edit and read mode.

I’m so glad I don’t have to wait for datacore to achieve this, I was getting worried :sweat_smile:

1 Like