Help with dataviewjs image rendering

I’d rather use something like the following:

```dataviewjs

const myImgFiles = app.vault.getFiles()
  .filter(file => file.extension === 'png' && 
                  file.path.includes('moon') && 
                  file.name.includes(dv.current().moonday))

if ( myImgFiles.length == 1 ) {
  dv.span(imgDisplay(myImgFiles[0].path))
} else {
  dv.span("Found none or more than one moon image")
}

function imgDisplay(imageLink) {
 return '<img src="' + app.vault.getResourcePath(dv.fileLink(imageLink)) + '" alt="right htiny clear-hr"/>'
}
```

This would be slightly better at picking out that one file and have logical handling if moonday was missing or the script would return multiple image file into myImgFiles.


Then again, this script was written for a specific scenario where it wasn’t using the getFiles() call, and in your case I believe the image path to these files are known in front of the script, so I’d rather use something like:

```dataviewjs
const imgLink = app.vault.getFileByPath("_img/" + dv.current().moonday + ".png")

if (imgLink) {
 dv.span('<img src="' + app.vault.getResourcePath(imgLink) +
         '" alt="right htiny clear-hr"/>')
} else {
  dv.span("Couldn't find moonday image for \`" + dv.current().moonday +"\`")
}
```

Of course you would need to change _img/ to the folder of your images.

But this would be a much cleaner way to display an image when you want to present just part of the name in your field. In general though I do believe it would be better in recent versions of Obsidian to have the full link in the frontmatter directly, as that would allow for link renaming, backlinks and so on to be properly recognised. And then the circle is complete by referring to where I originally defined this script in the post below:

1 Like