No more JavaScript in .tt files

Marc Bonsels21. Mar 2017 | DevelopmentMiscellaneous


If you are (for any reason) watching the OTRS repository on GitHub, you may have noticed a lot of commits last year on master, which were commented with something like “JavaScript refactoring”.

In case you were wondering what that was about, I’m glad to shed some light on it today. The main goal of this refactoring was to get rid of all JavaScript in the OTRS Template Toolkit (.tt) template files. In OTRS 5, nearly every .tt file which was responsible for providing the HTML code for a certain frontend contained a block like this:

[% WRAPPER JSOnDocumentComplete %]
<script type="text/javascript">//<![CDATA[
$('#FindSomeDomElement').on('something', function() {
[% END %]

It’s not very hard to recognize that this could become an issue when it comes to maintaining or extending code. It could even lead to code duplication because we ended up using the (nearly) same JavaScript code across different templates.

As you might have read in my previous post, one of our goals for OTRS 6 is to clean up such legacies, which is why we decided to move JavaScript code from almost all template files to proper libraries. In combination with the a new mechanism which allows JavaScript modules to initialize themselves, we now have a clear separation between HTML and JavaScript code.

Now, there may be cases when you need to transfer data from Perl to JavaScript. Up to OTRS 5, you would probably do something like this:

[% WRAPPER JSOnDocumentComplete %]
<script type="text/javascript">//<![CDATA[
var MyVariable = '[% Data.SomeDataFromPerl | JSON %]';
[% END %]

Now in OTRS 6, there is a new method called AddJSData() in Kernel::Output::HTML::Layout::Template which allows for collecting all data in Perl that you’d like to provide to JavaScript. Once you’ve called AddJSData(), all data you have provided will be available in JavaScript through the Core.Config.Get API. Example:

  • Perl
        Key   => 'MyKey',
        Value => \@MyArrayWithSomeData,
  • JavaScript
    var MyVariable = Core.Config.Get('MyKey');
    $.each(MyVariable, function(Index, Item) {

What you can also see in this example is that you don’t have to take care about the type of data you’re passing to JavaScript, because AddJSData will take care of it for you.

Your email address will not be published. Required fields are marked *