No more JavaScript in .tt files

Marc Bonsels21. Mar 2017 | DevelopmentMiscellaneous

Source: memegen.com

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[
Core.Some.Module.Init();
$('#FindSomeDomElement').on('something', function() {
   DoSomethingWithIt();
});
//]]></script>
[% 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 %]';
//]]></script>
[% 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
    $LayoutObject->AddJSData(
        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 *

This site uses cookies. By continuing to use the site, you agree to the use of cookies. More information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close