Some prerequisites to get started with dv.view() scripts
To do dv.view()
scripts you need to be able to create pure text files ending with .js
, and edit these in an external editor (that is unless you’ve got some plugins related to plaintext editing of files). A good alternative for at least Mac and Windows is VS Code.
It’s usually a good thing to keep these scripts within a dedicated folder in your vault, so for the rest of this post I’ll assume you’ll use vault/_js/
for all these script files, where vault
is the base path of your vault. If you change this to something else, you’ll also need to change all references to “_js/” to match that new folder.
The simple variant
The most barebone variant of such a script for displaying image would be to have the following in a _js/bareImg.js
:
const basePath = `file://${this.app.vault.adapter.basePath}/`
const imgFile = dv.current()[ input ]
return `<img src="${basePath}${imgFile}" />`
Usage: `dv.view(“_js/bareImg”, “cover”) `)
, where cover
refers to a field in the current file holding the full path of the image file, i.e. some/folder/myImage.png
This doesn’t allow for any styling beside what you enter directly into the <img>
tag in the script itself.
Advantage of this variant is that it’s the shortest footprint related to what you need to type within your table. One disadvantage is that it only uses fields defined within the current file.
With some styling options
Another slightly more advanced version, which I’m using in one of my vaults is this one (which I’ve stored as _js/img.js
):
const basePath = `file://${this.app.vault.adapter.basePath}/`
const imgFile = input.src
const style = input.style
return `<img src="${basePath}${imgFile}" style="${style}" />`
Usage: `$= dv.view(“_js/img”, {src: “some/image.png”, style:“width: 200px; height: 50px; float: right” }) `
This sets all of those html styles directly for the image, and allows for me to place and size (and whatever else is possible through the style
-attribute) for the image. The usage pattern is a little larger though, and I’m happy with defining the source directly in the call, so it’s not as easy to use in combination with an inline field (unless you modify the script a bit to match the first variant for the src
attribute).
Disclaimer: I’ve not tested this on the various platforms, and it might need adjusting especially for iOS or android, possibly.