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&up_source_language=' .. string.split(page.language !== '' ? page.language : site.language, '-', 2)[0] .. '&w=160&h=60&title=&border=&output=js'}}" />
</div>
Now, simply invoke the template on any page as follows:
{{ template.translate() }}
The result looks as follows: