This page is part of a static HTML representation of the TiddlyWiki at https://tiddlywiki.com/dev/

Hello World widget tutorial

16th February 2019 at 5:56pm

Now let's create a widget which actually has output.

When tiddlywiki encounters a widget definition like <$hello> it will create an object which is an instance of the class which is exported by the widget code.

In addition to creating an instance of the class, tiddlywiki will call the render method of the resulting object. The render method is expected to create a dom node which will be display in place of the widget.

In the donothing example the core widget was exported. The core widget class doesn't have a render method which creates a dom node and that's why there is no output. Getting output requires writing a widget class which inherits from the core Widget class. Code in the render method of this class will display the hello world message.

The hello.js tiddler has code which accomplishes that:

/*\

Hello, World widget

\*/
(function(){

/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";

var Widget = require("$:/core/modules/widgets/widget.js").widget;

var MyWidget = function(parseTreeNode,options) {
	this.initialise(parseTreeNode,options);
};

/*
Inherit from the base widget class
*/
MyWidget.prototype = new Widget();

/*
Render this widget into the DOM
*/
MyWidget.prototype.render = function(parent,nextSibling) {
	this.parentDomNode = parent;
	var textNode = this.document.createTextNode("Hello, World!");
	parent.insertBefore(textNode,nextSibling);
	this.domNodes.push(textNode);
};

exports.hello = MyWidget;

})();
The code for importing the core widget class remains, but now we also have code to create our own class which inherits from it. In addition an implementation of the render method is included. Here is the result:
[ { "title": "$:/DefaultTiddlers", "text": "[[hello world widget]]" } ] [ { "title": "hello.js", "text": "/*\\\n\nHello, World widget\n\n\\*/\n(function(){\n\n/*jslint node: true, browser: true */\n/*global $tw: false */\n\"use strict\";\n\nvar Widget = require(\"$:/core/modules/widgets/widget.js\").widget;\n\nvar MyWidget = function(parseTreeNode,options) {\n\tthis.initialise(parseTreeNode,options);\n};\n\n/*\nInherit from the base widget class\n*/\nMyWidget.prototype = new Widget();\n\n/*\nRender this widget into the DOM\n*/\nMyWidget.prototype.render = function(parent,nextSibling) {\n\tthis.parentDomNode = parent;\n\tvar textNode = this.document.createTextNode(\"Hello, World!\");\n\tparent.insertBefore(textNode,nextSibling);\n\tthis.domNodes.push(textNode);\n};\n\nexports.hello = MyWidget;\n\n})();\n", "created": "20190201114558816", "modified": "20190201224846870", "module-type": "widget", "tags": "", "type": "application/javascript" } ] [ { "title": "hello world widget", "text": "\n```\n<$hello/>\n```\n\nRenders as:\n\n<$hello/>\n" } ]