This is a stripped-down version of a single section of Grok TiddlyWiki, optimized for fast loading and readability by search engines. Some features are missing.

For the full Grok TiddlyWiki experience, please visit the wiki version of this page.

JavaScript Macros

2nd May 2021 at 11:27am

(Prerequisite for this section: Basic knowledge of JavaScript.)

If you want to do something that's just a little bit out of reach of a wikitext macro, you can also write macros in JavaScript. It's important that your macro execute quickly and have no side effects, as TiddlyWiki may repeatedly rerender the page containing the macro and call your JavaScript function in the process, just as it would with a wikitext macro. JavaScript macros also cannot access the browser DOM, since they may run server-side if you're serving your wiki with Node.js.

The process of creating a JavaScript macro is documented on the TiddlyWiki Dev wiki, although not particularly well. Let's suppose that we want a macro that rounds timestamps to the nearest 15 minutes. First, we write a JavaScript function that takes arguments matching those of the macro and returns the wikitext we want to output. You can test this function in any JavaScript development environment you like, including something as simple as your browser devtools. You'll end up with a single function, like this:

function(parameter) {
    /* do some stuff */
    return "my return value";
}

Then, we create a tiddler with type application/javascript and a field module-type set to macro. Drop in the following template snippet, then update the documentation comments and exports.name and exports.params variables as appropriate and assign your function to exports.run.

/*\
title: YOUR MACRO NAME
type: application/javascript
module-type: macro

DESCRIPTION OF YOUR MACRO
\*/
(function(){
"use strict";

exports.name = "YOUR MACRO NAME";
exports.params = [
    {name: "YOUR FIRST PARAMETER NAME"}
    /* repeat for additional parameters */
];
exports.run = /* INSERT YOUR FUNCTION HERE... */;

})();

When you change a JavaScript macro, you must reload the entire wiki for the changes to take effect, as TiddlyWiki doesn't dynamically reload JavaScript. It won't tell you to do so – this can be very puzzling if you aren't aware it's necessary!

After reloading the wiki, assuming you did everything right, your macro will be available for use in any tiddler just like any other global macro.

Exercises

Exercise: (M) [Ex:RoundtimeMacro]

Create a JavaScript macro called roundtime that rounds a TiddlyWiki-formatted timestamp to the nearest 15 minutes.

go to answer

Takeaways

Takeaways are not available in the static version of Grok TiddlyWiki. Visit the wiki version of this page to study takeaways.

↑ 8: Getting Technical