Dataview: reuse DQL queries?

Hi again all,

I’ve found something of a workaround, so I’d thought I’d share if anyone comes across this topic in the future.

We can take advantage of the fact that DataviewJS can execute DQL queries and use it to embed a DQL query that can be reused across multiple pages.

To do this, we create a DataviewJS script in our Scripts directory to embed a DQL query inside a dv.execute() block. Note that we use the backtick operator to create a multi-line string so the query looks natural.

Scripts/reusable-query.js

dv.execute(`

LIST ComplexField
FROM "Folder"
WHERE ...
FLATTEN ... as ComplexField
SORT ComplexField

`);

Then, in our target page, we include the script using a DataviewJS block (in this case I use an inline block).

Notes/MyPage.md

Here is the query:

`$= dv.view("/Scripts/reusable-query");`

Because dv.view() executes in the context of the embedding page, this DQL query can now be maintained in one place and reused across many pages, which was my primary goal.

This approach has some downsides though, including that the reusable DQL has to be kept as a .js file instead of a .md file, and so it’s not a first-class citizen of the Obsidian UI. For example, I can’t update the script from within Obisidan; I have to use a text editor for that.

However, overall I’m pretty pleased with this workaround, and I hope it’s helpful to someone else too.

15 Likes