Skip to content
BillyTom edited this page Jan 10, 2012 · 18 revisions

This tutorial leads you through all that is need to get started working with Sqwidget to build your own easily-deployable widget. We begin with a very simple embedded block of text and move all the way through to something more complex and more useful.

All the examples here are available in the sqwidget repository at https://github.com/premasagar/sqwidget/tree/master/tutorials/

But first, a little bit of architecture of Sqwidget will help you work out what we are trying to do.

A Sqwidget widget is put in a page using a small piece of html embed code that contains a <div> element that makes a place that the resulting widget will be put into, and a <script> element to load sqwidget.js, Sqwidget's core code. So, you need to put this embed code on any page where you want your widget to appear.

Here's the simplest possible embed code:

    <div data-sqwidget="src:widget-source-file.html"></div>
    <script type="text/javascript" charset="utf-8" src="sqwidget.js"></script>

How does this work? Well, once sqwidget.js is loaded it arranges to load jQuery for itself. Then, once the DOM is settled, sqwidget code is executed that goes and looks for any divs in the page that have a data-sqwidget attribute. In this case, the data-sqwidget attribute is set to src:widget-source-file.html. This tells sqwidget to load the widget source from widget-source-file.html and use that to populate this div with the widget-source-file.html widget.

So, what is a widget source and how does it work?

The widget source can be:

  • a plain text document
  • a snippet of html
  • a full html specification file, which can include:
    • a default template in the html <body> which is rendered into the widget
    • <style> elements in the <head> that are added to the destination page
    • JavaScript <script> elements that are configuration or widget controller code
    • Templates contained in <script type="text/template"> elements

So, let's start at the simplest and work up to a complex example.

Hello World

The simplest widget is a text string that can be embedded somewhere else. The embed code looks like this:

<div data-sqwidget="src:helloworld.html"></div>

and the source file helloworld.html looks like this:

hello world

The result here is that the string 'hello world' is embedded into the embed <div>. Simple, and useful it you need to embed a little text file from somewhere into a page.

Inserting an HTML snippet

<div data-sqwidget="src:hellohtml.html"></div>

and the source file hellohtml.html looks like this:

<strong>Colours</strong>
<ul>
    <li>red</li>
    <li>green</li>
    <li>blue</li>
</ul>

This inserts the given html snipped into the embed <div>. This is useful for putting a snippet of html from one place into another.

Using Templating

Further information on templating can be found on the Sqwidget Templating page