[Suggestion] Add {{#OnDesktop}}{{/OnDesktop}}

I feel like we shouldn’t tempt users to overuse conditional replacements for scripts. You could just assign a boolean for each client to globalThis:

var conditions = {
    AnkiDesktop: document.documentElement.className.split(/\s/).some(c => /linux|win|mac/.test(c)),
    AnkiWeb: /AnkiWeb/.test(document.querySelector("title").innerText),
    AnkiMobile: document.documentElement.classList.contains("safari"),
    AnkiDroid: globalThis.AnkiDroidJS != null,
}

Object.keys(conditions).forEach((key) => {
    globalThis[`is${key}`] = conditions[key];
});

… and then wrap your function calls with if blocks:

if (globalThis.isAnkiDesktop) {
  doSomething();
}
This particular set of conditions probably doesn’t allow separating between AnkiWeb and AnkiMobile on iOS.

Why?

In the past I also loved the conditional replacement feature and used it extensively in my templates (not just to wrap entire <script> tags, but for individual function calls). But there came a time when my template got too complex to code inside Anki, so I had to migrate to an IDE. From that point on I found the {{FieldName}} syntax to be a hindrance, as VS Code doesn’t understand it and marks it as invalid JS.

My point is, we should not incentivise people to use syntax that’s exclusive to Anki within their JavaScript when there are ways to achieve the same result without it.

3 Likes