Example of styling Dataview with variables

I have a dataview query that shows me all the notes created “on this day” in previous years. The notes that populate this query have a “date” property in the YAML (I supposed you could use “created” or “modified” here, but that didn’t work for me with files exported from other apps and I didn’t want to mess with trying to adjust the file creation date). Anyway, depending on which folder the note is in, I like it to have a colored border around, so it cues me what kind of a note it is.

const today = moment().format("MM-DD"); 
const days = dv.pages('"60 Practice/63 Journal/01 Journal" or "60 Practice/63 Journal/02 Commonplace Book" or "60 Practice/63 Journal/04 Practice Journal"').where(p => moment(String(p.date)).format("MM-DD") === today).groupBy(p => moment(String(p.date)).format("YYYY")); 

for (let group of days) 
{
dv.el("h1", group.key); 
for (let day of group.rows) 
{
  dv.el("p", dv.fileLink(day.file.path, true) +"\n"+dv.fileLink(day.file.path, false, "link"),{cls: day.file.path}) 
}
}

The key thing here to notice for the “styling” aspect is the {cls: day.file.path} part near the end. This says: create a class named for the path of the file.

Then, I use this CSS snippet:

.otd p[class*="02 Commonplace Book"] {
    border-radius: 15px;
	padding: 20px;
	margin-bottom:10px;
	border: 1.4em solid #797A78;
  }

This says, on any page with cssclass: otd in the YAML, apply this CSS. And the rules (I just show one above) say: in any class that contains the text string, apply this rule. Create different rules for different folder names.

You can abstract this out to a lot of different use cases. Depending on what variable you set in the class, you can then style it variably using this technique–it doesn’t have to be the path. Could be file name, could be day of week of the creation date, etc. etc.

Thanks to the folks on discord who helped me with the initial Dataview query!

(PS this may require the beta version of Dataview, which shouldn’t be too big a problem as I think the beta is becoming the regular version soon enough)

1 Like