MindTouch Developer Center > DekiScript > Samples/FAQ > How do I... Create a parametrized JavaScript widget?
Table of contents
No headers

This sample shows how to create a template that embeds a parametrized JavaScript widget.  For this sample, we're using the Google Translate widget, which can be embedded into a page and automatically translate it to a variety of languages.

To embed JavaScript code, you must have either ADMIN or UNSAFECONTENT permission.  If you don't, Deki Wiki will convert the <script> tag into a plain text and the JavaScript code will not execute.

The Google Translate widget requires as input the language from which to translate from.  Normally, this needs to be passed in explicitly, but Deki Wiki supports both language information per site and per page.  So, for this example, we can use this information to automatically select the right language for the widget.

The language used on the page is retrieve using page.language.  If no language is specified for the page, the result with be an empty string.  In this case, we need to check for the site language using site.language.  The following DekiScript fragment achieves this goal:

page.language !== '' ? page.language : site.language

   

We need overcome one last obstacle.  Deki Wiki may store both the primary and secondary language culture (e.g. "de-ch" for Swiss German).  However, Google Translate only expects the primary language culture.  So, we need to make sure we cut the language string up and return only the first part.  For this, we use the string.split function, which splits the string into substrings.  The following DekiScript achieves exactly that:

string.split(page.language !== '' ? page.language : site.language, '-', 2)[0]

   

Now, we're ready to dynamically compute the parameters to the src attribute on the <script> element.  Attributes can be dynamically computed by enclosing the attribute value in double brackets (i.e. {{ }}).  Putting it all together into a template, we get the following DekiScript code:

<h1>Template:Translate</h1>
<div style="float: right;">
<script src="{{'http://www.gmodules.com/ig/ifr?url=http://www.google.com/ig/modules/translatemypage.xml&amp;up_source_language=' .. string.split(page.language !== '' ? page.language : site.language, '-', 2)[0] .. '&amp;w=160&amp;h=60&amp;title=&amp;border=&amp;output=js'}}" />
</div>

Now, simply invoke the template on any page as follows:

{{ template.translate() }}

    

The result looks as follows:

Tag page
Viewing 2 of 2 comments: view all
What version of Deki Wiki does this work with?
Posted 19:11, 9 Jun 2008
I wasn't able to get this to work with wik.is. Am I using it incorrectly? I get the error "line 1, column 111: invalid Primary"
Posted 02:50, 16 Jul 2008
Viewing 2 of 2 comments: view all
You must login to post a comment.
Powered by MindTouch Deki v.8.08.1a